Table of contents
1.
Introduction
2.
What is AJAX?
3.
AJAX PHP Example
3.1.
HTML and JavaScript Code
4.
The PHP File: gethint.php
4.1.
PHP Code
4.2.
How It Works
5.
Client-Side HTML File
5.1.
Step 1: Create the Basic HTML Structure
5.2.
Step 2: Add JavaScript for AJAX
6.
Server-Side PHP File
6.1.
Step 1: Create the PHP File
6.2.
Step 2: Test the Setup
7.
Frequently Asked Questions
7.1.
What is the primary use of AJAX with PHP?
7.2.
Can AJAX only work with PHP?
7.3.
How can I modify the PHP file to fetch data from a database?
8.
Conclusion
Last Updated: Jan 12, 2025
Easy

AJAX and PHP

Author Sinki Kumari
0 upvote
Career growth poll
Do you think IIT Guwahati certified course can help you in your career?

Introduction

AJAX, which stands for Asynchronous JavaScript & XML, is a technique used in web development to create fast & dynamic web pages. It allows you to update parts of a web page without reloading the entire page. This makes websites faster & more user-friendly. PHP, on the other hand, is a server-side scripting language used to handle backend operations. When combined, AJAX & PHP can create powerful web applications that respond quickly to user actions.

AJAX and PHP

In this article, we will discuss what AJAX is, how it works with PHP, & how to implement it step by step. We will also look at examples of client-side HTML files & server-side PHP files to understand the process better.

What is AJAX?

AJAX is a set of web development techniques that allows web applications to send & receive data asynchronously from a server without interfering with the display & behavior of the existing page. This means you can update a part of a webpage without reloading the entire page. For example, when you type something into a search bar & suggestions pop up instantly, that’s AJAX at work.

AJAX is not a single technology but a combination of several technologies:

  • HTML & CSS for structuring & styling the content.
     
  • JavaScript for dynamically updating the content.
     
  • XMLHttpRequest (or Fetch API) for sending & receiving data from the server.
     
  • PHP or other server-side languages for processing the data.
     

The key advantage of AJAX is that it makes web applications faster & more responsive. Instead of waiting for the entire page to reload, only the necessary data is fetched & displayed. This improves the user experience significantly.

AJAX PHP Example

Let’s start with a simple example where we build a suggestion box. When a user starts typing in an input field, suggestions are fetched from the server without refreshing the page. Here’s how it works:

HTML and JavaScript Code

<!DOCTYPE html>
<html>
<head>
    <title>AJAX PHP Example</title>
    <script>
        function showHint(str) {
            if (str.length === 0) {
                document.getElementById("txtHint").innerHTML = "";
                return;
            }
            const xhttp = new XMLHttpRequest();
            xhttp.onreadystatechange = function () {
                if (this.readyState === 4 && this.status === 200) {
                    document.getElementById("txtHint").innerHTML = this.responseText;
                }
            };
            xhttp.open("GET", "gethint.php?q=" + str, true);
            xhttp.send();
        }
    </script>
</head>
<body>
    <h3>Type a name:</h3>
    <form>
        <input type="text" onkeyup="showHint(this.value)">
    </form>
    <p>Suggestions: <span id="txtHint"></span></p>
</body>
</html>


Output

Output

Explanation

  • HTML Structure: The input field triggers the showHint function every time the user types.
     
  • JavaScript Logic: An XMLHttpRequest object (xhttp) sends a request to the server (to the gethint.php file) with the user input (str).
     
  • Response Handling: When the server responds, the result is displayed inside the <span> tag with the ID txtHint.

The PHP File: gethint.php

This is the server-side script that processes the user’s input and returns suggestions.

PHP Code

<?php
// Array of names
$names = ["Alice", "Bob", "Charlie", "David", "Eve", "Frank", "Grace"];

// Get the parameter from URL
$q = $_GET['q'] ?? "";

$suggestion = "";

if ($q !== "") {
    $q = strtolower($q);
    $len = strlen($q);
    foreach ($names as $name) {
        if (stristr(substr($name, 0, $len), $q)) {
            $suggestion .= $suggestion === "" ? $name : ", $name";
        }
    }
}
echo $suggestion === "" ? "no suggestion" : $suggestion;
?>
You can also try this code with Online PHP Compiler
Run Code


Output 

"no suggestion" if nothing matches

 

Explanation of the PHP Code

  1. Input Handling: The script retrieves the user’s input (q) from the URL using $_GET.
     
  2. Matching Logic: It loops through an array of predefined names, checking if the input matches the start of any name.
     
  3. Response Generation: If matches are found, they are combined into a single string and returned as the response.
     
  4. Default Response: If no matches are found, it returns "no suggestion."

How It Works

  1. The user types in the input field.
     
  2. The JavaScript function sends the input to gethint.php.
     
  3. The PHP script processes the input and sends back matching names.
     
  4. The browser updates the suggestion box without reloading the page.

Example Output

Input: D
Output: David
Input: E
Output: Eve
Input: Z
Output: no suggestion


Example Explained

  • Dynamic Interactions: AJAX allows you to fetch data asynchronously, giving users a seamless experience.
     
  • Code Efficiency: With minimal code, you’re able to perform server-side processing and update the UI dynamically.
     
  • Customizability: You can modify the PHP file to fetch data from a database, making it suitable for real-world applications.

Client-Side HTML File

The client-side HTML file is where the user interacts with the web application. It includes the structure of the page & the JavaScript code that makes AJAX requests to the server. Let’s understand this in step by step manner: 

Step 1: Create the Basic HTML Structure

First, we need to create a simple HTML file. This file will include a form where users can input data & a section to display the response from the server.

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>AJAX with PHP Example</title>
</head>
<body>
    <h1>AJAX & PHP Example</h1>
    <form id="myForm">
        <label for="name">Enter your name:</label>
        <input type="text" id="name" name="name" required>
        <button type="submit">Submit</button>
    </form>

    <div id="response"></div>

    <script>
        // JavaScript code will go here
    </script>
</body>
</html>


In this code:

  • We have a simple form with an input field for the user’s name & a submit button.
     
  • There’s a `<div>` with the ID `response` where we’ll display the server’s response.

Step 2: Add JavaScript for AJAX

Next, we need to write JavaScript to handle the form submission & send an AJAX request to the server. We’ll use the `XMLHttpRequest` object for this.

<script>
    document.getElementById('myForm').addEventListener('submit', function(event) {
        event.preventDefault(); // Prevent the form from submitting the traditional way
        // Get the input value
        var name = document.getElementById('name').value;
        // Create a new XMLHttpRequest object
        var xhr = new XMLHttpRequest();


        // Define the type of request, the URL, & whether it should be asynchronous
        xhr.open('POST', 'server.php', true);

        // Set the request header to specify the content type
        xhr.setRequestHeader('Content-Type', 'application/x-www-form-urlencoded');


        // Define what happens when the server responds
        xhr.onreadystatechange = function() {
            if (xhr.readyState === 4 && xhr.status === 200) {
                // Update the response div with the server's response
                document.getElementById('response').innerHTML = xhr.responseText;
            }
        };
        // Send the request with the form data
        xhr.send('name=' + encodeURIComponent(name));
    });
</script>


In this code:

1. Prevent Default Form Submission: We use `event.preventDefault()` to stop the form from submitting the traditional way, which would reload the page.
 

2. Get Input Value: We retrieve the value entered by the user in the input field.
 

3. Create XMLHttpRequest Object: This object is used to send & receive data from the server.
 

4. Open Connection: We specify the type of request (`POST`), the URL of the server-side script (`server.php`), & set it to be asynchronous (`true`).
 

5. Set Request Header: We tell the server that we’re sending form data.
 

6. Handle Server Response: When the server responds, we check if the request is complete (`readyState === 4`) & successful (`status === 200`). If so, we update the `response` div with the server’s response.
 

7. Send Request: We send the request to the server with the user’s input.

Server-Side PHP File

The server-side PHP file handles the data sent by the client-side HTML file & processes it. It then sends a response back to the client. Let’s create a simple PHP file named `server.php` to handle the AJAX request.

Step 1: Create the PHP File

Create a new file named `server.php` in the same directory as your HTML file. This file will receive the data sent by the AJAX request, process it, & return a response

<?php
// Check if the request method is POST
if ($_SERVER['REQUEST_METHOD'] === 'POST') {
    // Get the data sent from the client
    $name = isset($_POST['name']) ? $_POST['name'] : '';


    // Validate the input (optional but recommended)
    if (!empty($name)) {
        // Process the data (e.g., save to a database, perform calculations, etc.)
        $response = "Hello, " . htmlspecialchars($name) . "! Your name was received successfully.";
    } else {
        // Handle empty input
        $response = "Please enter a valid name.";
    }


    // Send the response back to the client
    echo $response;
} else {
    // Handle invalid request methods
    echo "Invalid request method.";
}
?>


In this Code:

1. Check Request Method: We first check if the request method is `POST` using `$_SERVER['REQUEST_METHOD']`. This ensures that the script only processes POST requests.
 

2. Retrieve Data: We use `$_POST['name']` to get the data sent from the client. The `isset()` function checks if the `name` field exists in the POST request.
 

3. Validate Input: We check if the `name` field is not empty. This is optional but recommended to ensure valid data is processed.
 

4. Process Data: If the input is valid, we process it. In this example, we simply create a response message that includes the user’s name. The `htmlspecialchars()` function is used to prevent XSS (Cross-Site Scripting) attacks by converting special characters to HTML entities.
 

5. Handle Empty Input: If the input is empty, we return an error message asking the user to enter a valid name.
 

6. Send Response: Finally, we use `echo` to send the response back to the client. This response will be displayed in the `response` div of the HTML file.
 

7. Handle Invalid Requests: If the request method is not `POST`, we return an error message indicating an invalid request method.

Step 2: Test the Setup

To test this setup:

1. Save the HTML file as `index.html` & the PHP file as `server.php` in the same directory.

 

2. Open the `index.html` file in a web browser.
 

3. Enter your name in the input field & click the submit button.
 

4. The response from the server (e.g., "Hello, [Your Name]! Your name was received successfully.") should appear in the `response` div without reloading the page.

Frequently Asked Questions

What is the primary use of AJAX with PHP?

AJAX with PHP is used to create interactive web applications that can update content dynamically without reloading the entire webpage. It enhances the user experience by providing real-time interactions.

Can AJAX only work with PHP?

No, AJAX can work with any server-side language, such as Python, Java, or Node.js. PHP is commonly used due to its simplicity and compatibility with web servers.

How can I modify the PHP file to fetch data from a database?

You can replace the array in the PHP script with a database query using SQL. 

Conclusion

In this article, we discussed how to use AJAX with PHP to create dynamic, interactive web applications. From setting up the front-end HTML and JavaScript to implementing the server-side PHP script, this guide walked you through every step with examples. 

You can also check out our other blogs on Code360.

Live masterclass