Ugacomp

A Beginner’s Guide to AJAX & Asynchronous Programming in PHP

Where necessary, you may need to have access to a VPS server so you can follow how to implement the steps in this article.  You can get a cheaper VPS Server from Contabo with 4vCPU cores, 8GM RAM, and 32TB Bandwidth for less than $5.50 per month. Get this deal here now

Table of Contents

Cloud VPS S

$5.50 Monthly
  • 4 vCPU Cores | 8GB RAM

CLOUD VPS M

$15.50 Monthly
  • 6 vCPU Cores | 16GB RAM

CLOUD VPS L

$17.50 Monthly
  • 8 vCPU Cores | 24GB RAM

As web applications become more dynamic and user-friendly, the need for asynchronous programming becomes crucial. AJAX (Asynchronous JavaScript and XML) is a powerful technique that allows web pages to be updated asynchronously by exchanging small amounts of data with the server behind the scenes. In this guide, we will explore the basics of AJAX and asynchronous programming in PHP, providing beginners with a solid foundation.

AJAX Basic syntaxes for PHP

AJAX enables web pages to be updated asynchronously, meaning that specific parts of a page can be updated without requiring a full page refresh. This results in a smoother and more responsive user experience. AJAX is based on a combination of technologies, including HTML, CSS, JavaScript, and XML (though JSON is more commonly used today).

Before diving into AJAX programming with PHP, make sure you have a development environment set up. You can use tools like XAMPP, WampServer, or any other local server environment to run PHP scripts.

When working with PHP, AJAX allows you to make asynchronous requests to the server, update parts of a web page without reloading the entire page, and provide a seamless user experience. Let’s explore the basic syntax for implementing AJAX in PHP.

AJAX Request Setup

At the core of AJAX is the XMLHttpRequest object, which is used to interact with the server. Here’s a basic outline of the AJAX request setup in JavaScript:

JavaScript (client-side)

// Creating an XMLHttpRequest object
var xhr = new XMLHttpRequest();

// Configuring the request (method, URL, asynchronous flag)
xhr.open('GET', 'ajax_handler.php', true);

// Setting up the callback function to handle the response
xhr.onreadystatechange = function () {
    if (xhr.readyState === 4 && xhr.status === 200) {
        // Code to handle the response
        console.log(xhr.responseText);
    }
};

// Sending the request
xhr.send();

In this example, we create an XMLHttpRequest object, configure the request with the method (GET or POST), URL, and an asynchronous flag. We set up an event listener (onreadystatechange) to handle the response when the state of the request changes, and finally, we send the request.

PHP Script Handling AJAX Request

On the server side, a PHP script is needed to handle the AJAX request. Below is a basic PHP script (‘ajax_handler.php’) that processes the request and sends a response back:

PHP (server-side)

<?php
// Handle AJAX request
if ($_SERVER['REQUEST_METHOD'] === 'GET') {
    // Simulate data processing
    $data = "Hello from PHP!";

    // Simulate a delay (optional)
    sleep(2);

    // Return the processed data
    echo $data;
} else {
    // Handle other HTTP methods if necessary
    http_response_code(405); // Method Not Allowed
    echo "Invalid request method.";
}
?>

This PHP script checks if the request method is GET, simulates some data processing, and then echoes the processed data back to the client-side JavaScript. You can extend this script to handle other HTTP methods or perform more complex operations.

Now that we’ve covered the basics of setting up an AJAX request with PHP, let’s explore how to handle the response and deal with errors gracefully.

Handling AJAX Response

Once the server processes the AJAX request, you need to handle the response on the client side. Update the JavaScript code as follows:

JavaScript (client-side)

// Creating an XMLHttpRequest object
var xhr = new XMLHttpRequest();

// Configuring the request (method, URL, asynchronous flag)
xhr.open('GET', 'ajax_handler.php', true);

// Setting up the callback function to handle the response
xhr.onreadystatechange = function () {
    if (xhr.readyState === 4) {
        // Check if the request was successful
        if (xhr.status === 200) {
            // Code to handle a successful response
            console.log("Response from PHP:", xhr.responseText);
        } else {
            // Code to handle an unsuccessful response
            console.error("Error:", xhr.status, xhr.statusText);
        }
    }
};

// Sending the request
xhr.send();

In this modified code, we’ve added a check for the xhr.status to distinguish between successful and unsuccessful responses. If the status is 200 (OK), the response is considered successful, and you can proceed to handle the data. Otherwise, an error is logged with the status and status text.

Error Handling in PHP

When dealing with more complex scenarios, it’s essential to handle errors on the server side. Modify the PHP script to handle errors and provide appropriate responses:

PHP (server-side)

<?php
// Handle AJAX request
if ($_SERVER['REQUEST_METHOD'] === 'GET') {
    // Simulate data processing
    $data = "Hello from PHP!";

    // Simulate a delay (optional)
    sleep(2);

    // Simulate an error (for demonstration purposes)
    $error = false;

    if ($error) {
        http_response_code(500); // Internal Server Error
        echo "Error processing request.";
    } else {
        // Return the processed data
        echo $data;
    }
} else {
    // Handle other HTTP methods if necessary
    http_response_code(405); // Method Not Allowed
    echo "Invalid request method.";
}
?>

In this example, we’ve introduced a variable $error to simulate an error condition. If an error occurs, the script responds with a 500 Internal Server Error status code and an error message. Adjust this logic based on your application’s error-handling requirements.

.

Updating HTML Elements

A common use case for AJAX is updating HTML elements without refreshing the entire page. Let’s modify our JavaScript code to update a specific element on the page with the response from the server.

JavaScript (client-side)

// Creating an XMLHttpRequest object
var xhr = new XMLHttpRequest();

// Configuring the request (method, URL, asynchronous flag)
xhr.open('GET', 'ajax_handler.php', true);

// Setting up the callback function to handle the response
xhr.onreadystatechange = function () {
    if (xhr.readyState === 4) {
        // Check if the request was successful
        if (xhr.status === 200) {
            // Update a specific HTML element with the response
            document.getElementById('output').innerHTML = xhr.responseText;
        } else {
            // Code to handle an unsuccessful response
            console.error("Error:", xhr.status, xhr.statusText);
        }
    }
};

// Sending the request
xhr.send();

In this example, we’ve added a line of code to update an HTML element with the id ‘output’ using document.getElementById('output').innerHTML. You can replace ‘output’ with the id of the element you want to update.

Using JSON for Data Exchange

While our previous examples used plain text responses, it’s common to exchange data in JSON format. JSON is more flexible and easier to handle, especially when dealing with complex data structures.

JavaScript (client-side)

// Creating an XMLHttpRequest object
var xhr = new XMLHttpRequest();

// Configuring the request (method, URL, asynchronous flag)
xhr.open('GET', 'ajax_handler_json.php', true);

// Setting up the callback function to handle the response
xhr.onreadystatechange = function () {
    if (xhr.readyState === 4) {
        // Check if the request was successful
        if (xhr.status === 200) {
            // Parse the JSON response
            var data = JSON.parse(xhr.responseText);

            // Access data properties and update HTML elements
            document.getElementById('username').innerHTML = data.username;
            document.getElementById('email').innerHTML = data.email;
        } else {
            // Code to handle an unsuccessful response
            console.error("Error:", xhr.status, xhr.statusText);
        }
    }
};

// Sending the request
xhr.send();

This modification assumes that the server script (‘ajax_handler_json.php’) returns JSON-encoded data. The JavaScript code uses JSON.parse to convert the JSON response into a JavaScript object, making it easier to work with.

JSON Response in PHP

Update the PHP script to return a JSON response:

PHP (server-side)

<?php
// Handle AJAX request
if ($_SERVER['REQUEST_METHOD'] === 'GET') {
    // Simulate data processing
    $data = [
        'username' => 'JohnDoe',
        'email' => '[email protected]',
    ];

    // Simulate a delay (optional)
    sleep(2);

    // Simulate an error (for demonstration purposes)
    $error = false;

    if ($error) {
        http_response_code(500); // Internal Server Error
        echo json_encode(['error' => 'Error processing request.']);
    } else {
        // Return the processed data as JSON
        header('Content-Type: application/json');
        echo json_encode($data);
    }
} else {
    // Handle other HTTP methods if necessary
    http_response_code(405); // Method Not Allowed
    echo "Invalid request method.";
}
?>

In this example, we’ve modified the PHP script to return data as a JSON-encoded string using json_encode. The response’s content type is set to ‘application/json’ to inform the client that it should expect JSON data.

Implementing AJAX with Form Submission in PHP

Now, let’s take a step further and explore how to use AJAX to submit form data asynchronously, enhancing the user experience by avoiding full-page reloads.

First, let’s create a simple HTML form that users can submit:

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Form Submission with AJAX</title>
</head>
<body>

<form id="myForm">
    <label for="username">Username:</label>
    <input type="text" id="username" name="username" required>

    <label for="email">Email:</label>
    <input type="email" id="email" name="email" required>

    <button type="button" onclick="submitForm()">Submit</button>
</form>

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

<script>
    function submitForm() {
        // Get form data
        var formData = new FormData(document.getElementById('myForm'));

        // Creating an XMLHttpRequest object
        var xhr = new XMLHttpRequest();

        // Configuring the request (method, URL, asynchronous flag)
        xhr.open('POST', 'submit_form.php', true);

        // Setting up the callback function to handle the response
        xhr.onreadystatechange = function () {
            if (xhr.readyState === 4) {
                // Check if the request was successful
                if (xhr.status === 200) {
                    // Update a specific HTML element with the response
                    document.getElementById('response').innerHTML = xhr.responseText;
                } else {
                    // Code to handle an unsuccessful response
                    console.error("Error:", xhr.status, xhr.statusText);
                }
            }
        };

        // Sending the request with form data
        xhr.send(formData);
    }
</script>

</body>
</html>

This HTML file contains a simple form with fields for a username and email. The form data will be submitted asynchronously using AJAX.

PHP Script for Form Submission

Create a PHP script (submit_form.php) to handle the form submission on the server side:

PHP (submit_form.php)

<?php
// Handle AJAX form submission
if ($_SERVER['REQUEST_METHOD'] === 'POST') {
    // Get form data
    $username = $_POST['username'];
    $email = $_POST['email'];

    // Process the data (you can perform database operations or other tasks here)

    // Simulate a delay (optional)
    sleep(2);

    // Simulate an error (for demonstration purposes)
    $error = false;

    if ($error) {
        http_response_code(500); // Internal Server Error
        echo "Error processing form submission.";
    } else {
        // Return a success message
        echo "Form submitted successfully!";
    }
} else {
    // Handle other HTTP methods if necessary
    http_response_code(405); // Method Not Allowed
    echo "Invalid request method.";
}
?>

In this PHP script, we retrieve the form data using $_POST, process the data (you can perform database operations or other tasks here), simulate a delay, and simulate an error for demonstration purposes.

Hire us to handle what you want

Hire us through our Fiverr Profile and leave all the complicated & technical stuff to us. Here are some of the things we can do for you:

  • Website migration, troubleshooting, and maintenance.
  • Server & application deployment, scaling, troubleshooting, and maintenance
  • Deployment of Kubernetes, Docker, Cloudron, Ant Media, Apache, Nginx,  OpenVPN, cPanel, WHMCS, WordPress, and more
  • Everything you need on AWS, IBM Cloud, GCP, Azure, Oracle Cloud, Alibaba Cloud, Linode, Contabo, DigitalOcean, Ionos, Vultr, GoDaddy, HostGator, Namecheap, DreamHost, and more.
 

We will design, configure, deploy, or troubleshoot anything you want. Starting from $10, we will get your job done in the shortest time possible. Your payment is safe with Fiverr as we will only be paid once your project is completed.