Thursday, 23 July 2020

Make Ajax requests from the Web API XMLHttpRequest

JavaScript  PHP  HTML 

In the post Make Ajax requests from jQuery, we show you how to make Ajax requests by using the jQuery ajax() function. Here, we use the JavaScript object XMLHttpRequest (XHR) to do the same thing.

XMLHttpRequest is the other option for developers in Ajax programming. Not just XML, it can be used to fetch any type of data from a server asynchronously. It allows to update parts of a web page without reloading the whole page. To try how it works, just add a button in a web page to trigger an user event to make an Ajax request to the server.

<button id="demo" onclick="makeAjaxCall()">Call PHP</button>


In JavaScript, we make the function makeAjaxCall() to handle the button click event and make an Ajax request by using XMLHttpRequest.

function makeAjaxCall(){
        var request = new XMLHttpRequest();
        request.open('POST', 'my-backend.php');

        var student = {"name":"Tom", "sex":"M", "age":"11", "class":"6Y"};
        request.send(JSON.stringify(student));

        request.onload = function() {
            if (request.readyState == 4) {
                //the operation is done
                if (request.status == 200) {
                    alert(request.response);
                } else if (request.status >= 400){
                    //client or server errors
                    alert('Error Code: ' + request.status + ' Error Msg: ' + request.statusText);
                }

            }

        }

    }

First, the object XMLHttpRequest is initialized.

var request = new XMLHttpRequest();

Then, its method open() is called to create a new request. The first parameter defines the request method POST. The second parameter is for the URL to send the request to. Here, we set it as the backend PHP file my-backend.php. In line 5, we define a data object student for storing a student's personal data. The XMLHttpRequest method send() is called to send the request to the server with the data student. The JavaScript function JSON.stringify() is used to convert the object student to a JSON string before it is sent to the server. The XMLHttpRequest onload property is set as a callback function that will be called when the request transaction completes successfully.

After the request is sent, the XMLHttpRequest client will be in following states:

  • 0 UNSENT
  • 1 OPENED
  • 2 HEADERS_RECEIVED
  • 3 LOADING
  • 4 DONE


In XMLHttpRequest's onload callback function, we can check the request.readyState property for its state. If it is equal to 4, it means the operation is done. Then, we continue to check the HTTP status code of the XMLHttpRequest's response request.status. If it is equal to 200, it means that the request has succeeded and we can display the data returned from the server.

alert(request.response);

The HTTP response status codes are grouped in following classes:

  • Informational responses (100–199)
  • Successful responses (200–299)
  • Redirects (300–399)
  • Client errors (400–499)
  • Server errors (500–599)

In the JavaScript code snippet above, if the XMLHttpRequest's response status request.status is equal to 400 or over, we will display the error message.

alert('Error Code: ' + request.status + ' Error Msg: ' + request.statusText);

Same as in the post Make Ajax requests from jQuery, the backend PHP file my-backend.php gets the JSON data posted to the server, decodes it and outputs the student's name $data->name to the client side.

<?php

$json = file_get_contents('php://input');
$data = json_decode($json);
echo $data->name;

?>


References

HTTP response status codes
XMLHttpRequest.readyState


Search