Hyvor Developer

AJAX Request Handler with PHP

AJAX is a Web Technology to create asynchronous Web applications. AJAX allows web pages to communicate with the server behind the scenes. The web page can be updated dynamically without reloading.

In this tutorial, we will be discussing about how to write a PHP script to handle an ajax request and send a response back to the client. There are some tasks that handler should do.

  • Read input variables correctly
  • Handle errors
  • Do the process without any error
  • Send an appropriate response
This tutorial covers all of above steps with examples. I have separated the tutorial into subtopics for your ease.

Sending the Ajax Request

To perform an Ajax request, some javascript code must be implemented in the web page. But, I do not explain AJAX in Javascript deeply here. I assume that you have a basic knowledge on json too.

First, I've created a new page, index.html. I have written JS code in it to send an Ajax request to the server with some data. I have used pure javascript in the following example. If you like, you can use your desired JS library.



<script type="text/javascript">
    
    var http = new XMLHttpRequest();
    var data = "username=" + name + '&email=' + email;

    http.onreadystatechange = function() {
        if (this.readyState == 4 && this.status == 200) {
            // then handle the response
        }
    }

    http.open('ajax.php', 'POST', true);
    http.send(data);

</script>   



  • In first line of Javascript, I have initiated the XMLHttpRequest, which is the basis of Ajax.
  • Then I have declared the data variable to save the data that will be sent to the handler. Here I have set data variable to a URL string. If you use a library like jQuery, you can easily reach the target by just declaring an object.
  • Then, I have set the onreadystatechange method of XHR object.
  • Finally, I have opened the connection and sent the request to the server with data.

Later, I will explain more about how to handle the response and how to parse it as JSON.

Create the PHP Handler

Next, I have created the PHP handler, handler.php to handle the Ajax request. It will look like following.






Haha, it's just a blank file. Jump to the next step!

Include Necessary Files

Now, I have included two files that I need in handler.php. First one is the autoload file to autoload class files. (If you are interested, you can follow our autoloading tutorial to learn more). The second one is the database connection file. You can include files according to your needs. I just included these files to show that you can include any php file that you need to execute. So, I won't be using these files anymore hereafter in this tutorial.



<?php

include_once $_SERVER['DOCUMENT_ROOT'] . '/inc/autoload.php';
include_once $_SERVER['DOCUMENT_ROOT'] . '/inc/db.php';



Important!

When Ajax was introduced it was used with XML. But in the present, 99% of developers use JSON because it is lightweight and simple than XML. So, I'll be working with JSON objects hereafter. There are two PHP functions to use to handle JSON objects: json_encode and json_decode. There's no problem even you haven't heard of those functions because it's easy to understand.

There's another problem! When the server sends a response in JSON format, server has to tell the browser that the response is in JSON format. So, it's compulsory to add following code into every PHP script that handles Ajax requests.



header('Content-type: application/json');



However, It isn't a good idea to add above code in each script. So, including is a great trick. Therefore, I have created ajax.inc.php to save that code as well as to include other files.



<?php

header('Content-type: application/json');


// you can include any script that you need in every ajax handler (optional)

include_once $_SERVER['DOCUMENT_ROOT'] . '/inc/autoload.php';
include_once $_SERVER['DOCUMENT_ROOT'] . '/inc/db.php';



Then, I just have to include ajax.inc.php in my Ajax handlers. Let's focus on handler.php again. It would be like following



<?php

include_once $_SERVER['DOCUMENT_ROOT'] . '/inc/ajax.inc.php'; 

// ajax.inc.php is the file we created in the last step



Handling Errors

Handling errors is the most important part in the Ajax Handler. There are many ways to implement error handling. But, try-catch model is the best and the most efficient approach according to my personal experience. It's pretty simple to use. I can send an error message to the client (or the browser) just with throwing an error in PHP after implementing this model. Let's see how to implement it and response to error PHP catches in runtime.



<?php

include_once $_SERVER['DOCUMENT_ROOT'] . '/inc/ajax.inc.php'; 

try { 

    throw new Exception('Something Went Wrong', 512);


} catch(Exception $e) {
    
    echo json_encode(
        array(
            'status' => false,
            'error' => $e -> getMessage(),
            'error_code' => $e -> getCode()
        )
    );

    // do some process if needed. ex: MYSQL Rollbacks

    exit;

}



  • First, I have included the files.
  • Then, wrapped all the code with a try block
  • PHP process goes inside the try block. You can throw a Exception in runtime with a message and an error code. (error code is optional). The catch block will catch any Exception, even it is thrown by a method inside a class.
  • I have used throw new Exception statement to throw errors. First parameter is the error message and the second one is the error code
  • After catching the thrown error, I have echoed a string that is encoded in JSON which is originally a PHP Array. I have separated the code into parts below to make it easier to understand.


$arr = array(
    'status' => false,
    'error' => $e -> getMessage(),
    'error_code' => $e -> getCode()
);

$arr = json_encode($arr);

echo $arr;

exit;



  • First, I have created a key-value array which has 3 keys. First two are really important to show an error to the user in the browser and to browser to detect that the Ajax process wasn't successful. I have set status to false, which will be used later in this tutorial in the front-end (Javascript). $e -> getMessage() returns the string that was defined in the throw statement. It will return an empty string if the string isn't defined in the statement. Error code is optional to send to the browser, but you can make your application more organized by sending error codes. $e -> getCode returns the error code defined in the throw statement. The default value is 0.
  • Next, I have encoded the array in JSON format with json_encode function. That function returns a json encoded string that you don't need to take care of. PHP makes it easy to encode and it's really easy to decode it in Javascript too.
  • Next, I have echoed the json encoded string.
  • Finally, I have exited the script. You can add any code to do some task before you exit the script.

I know it's a long tutorial, Let's take a break! I have a question for you. Why do you exit the script just after finding an error on processing? Let me know your opinion by commenting below.

Okay. Next I'll show you some examples on error handling in Ajax scripts. These are some common places that you might want to throw errors and exit the script.

1. On a Database Query Error


$result = $mysqli -> query("UPDATE users SET username = $username");

if ($result === false) {
    throw new Exception('DB Query Failed', 202);
}



2. On Invalid Input


if (empty($_POST['email'])) {
    throw new Exception('Invalid Input', 200);
} else {
    $email = $_POST['email'];
}



You can use throw statement whenever you need to stop the process and send an error message to the browser.

So, I am going to finish my handler.php. It will throw an error if the request is a GET request.



<?php

include_once $_SERVER['DOCUMENT_ROOT'] . '/inc/ajax.inc.php'; 

try { 

    if ($_SERVER['REQUEST_METHOD'] !== "POST") {
        throw new Exception('Invalid Request', 2000);
    } else {
        // status is true if everything is fine
        exit(json_encode(
            array(
                'status' => true
            )
        ));
    }


} catch(Exception $e) {
    
    echo json_encode(
        array(
            'status' => false,
            'error' => $e -> getMessage(),
            'error_code' => $e -> getCode()
        )
    );

    exit;

}



Complete the Front-End

Let's consider about our JS code again. The final code in index.html will be like following.



<script type="text/javascript">

    function jsonParse() {
        try {
            var json = JSON.parse(text);
        } 
        catch(e) {
            return false;
        }
        return json;
    }
    
    var http = new XMLHttpRequest();
    var data = "username=" + name + '&email=' + email;

    http.onreadystatechange = function() {
        if (this.readyState == 4 && this.status == 200) {
            var json = jsonParse(this.responseText);

            if (!json || json.status !== true) {
                console.log(json.error || 'Something Bad Happened');
                return;
            }    

            alert('Everything is Fine!');

        }
    }

    http.open('ajax.php', 'POST', true);
    http.send(data);

</script>   



  • Mind that jsonParse() is not a native function. I have created it to parse JSON because Javascript engine throws errors if the string is not in the correct form. It has a in-built error handler. It returns the parsed object on success, otherwise false.
  • Then I have updated the onreadystatechange function to handle the response from the server.
  • I have assigned the variable json to save the return value of jsonParse function.
  • Next, It checks whether json variable is false. If it's true, it checks whether the status sent by the server isn't true. If any of those conditions are true, it will log an error to the console. You can even show the error to the user using DOM, if needed.
  • If json is true and status property of json is true process continues. Browser will alert the text in the code.

Finally...

Ajax is the best and most popular way to create a dynamic website. It is a must to have knowledge on how to create a PHP handler for Ajax requests, if you are a PHP developer. We have discussed about creating a PHP handler with examples. If you have any question to ask, feel free to comment below.

Author SupunKavinda