DEV Community

Yongyao Yan
Yongyao Yan

Posted on • Originally published at codebilby.com

Make Ajax Requests in JavaScript

Ajax is a set of web development techniques on the client side to exchange data with a server asynchronously. It allows updating parts of a web page dynamically without the need of reloading the whole page. In this post, we show you how to make Ajax requests by using jQuery and XMLHttpRequest object.

jQuery

The jQuery JavaScript library allows developers to use Ajax easily.
The jQuery ajax() method is used on the client side to make an Ajax request asynchronously.
To use the jQuery library, we need to reference it with the HTML <script> tag inside the <head> section.

<head>
    <!-- other codes ... -->
    <script src="https://code.jquery.com/jquery-3.5.1.min.js" 
    integrity="sha256-9/aliU8dGd2tb6OSsuzixeV4y/faTqgFtohetphbbj0=" 
    crossorigin="anonymous"></script>
    <!-- other codes ... -->
</head>
Enter fullscreen mode Exit fullscreen mode

By including the jQuery library file from a CDN (Content Delivery Network) as shown above, we don't need to download and host the library file. The integrity and crossorigin attributes are used to verify the resource by using the Subresource Integrity (SRI) checking.

We can add a button on the web page for calling the backend PHP.

<button id="demo">Call PHP</button>
Enter fullscreen mode Exit fullscreen mode

The following JavaScript code block is for the button click event.
When the button is clicked, the jQuery ajax() method will perform an Ajax request to the backend PHP.

<script>
    $(document).ready(function() {
        $("#demo").click(function(){
            var student = {"name":"Tom", "sex":"M", "age":"11", "class":"6Y"};
            $.ajax({
                type: 'POST',
                url: 'my-backend.php',
                data: JSON.stringify(student),
                success: function(data, textStatus, xhr) {
                    alert(data);
                },
                error: function(xhr, textStatus, errorThrown) {
                    alert('Error Msg: ' + errorThrown);
                }
            });        
        });
    });
</script>
Enter fullscreen mode Exit fullscreen mode

The JavaScript variable student defines an object that stores a student's personal data. In the ajax() method, we set the request type to POST. In url, we set the PHP file that will receive the request. The JavaScript function JSON.stringify() is used to convert the object student to a JSON string before it is sent to the server. The functions in success and error will be called respectively when the request succeeds or fails. Here, an alert box with the data returned from the server will display if the request succeeds. If it fails, an alert box will display the textual portion of the HTTP status errorThrown.

In the backend PHP file my-backend.php, we can do like this:

<?php
    $json = file_get_contents('php://input');
    $data = json_decode($json);
    echo $data->name;
?>
Enter fullscreen mode Exit fullscreen mode

The function file_get_contents() is used to get the data sent to the server. The function json_decode() is then called to convert the JSON encoded string $json into a PHP variable $data. Finally, the student's name $data->name is returned to the client side.

XMLHttpRequest object

XMLHttpRequest (XHR) 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 updating 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 a user event to make an Ajax request to the server.

<button id="demo" onclick="makeAjaxCall()">Call PHP</button>
Enter fullscreen mode Exit fullscreen mode

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);
                }

            }

        }

    }
Enter fullscreen mode Exit fullscreen mode

First, the object XMLHttpRequest is initialized.

var request = new XMLHttpRequest();
Enter fullscreen mode Exit fullscreen mode

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. 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 the 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);
Enter fullscreen mode Exit fullscreen mode

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);
Enter fullscreen mode Exit fullscreen mode

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;

?>
Enter fullscreen mode Exit fullscreen mode

References

HTTP response status codes

XMLHttpRequest.readyState

Thanks for reading!
To find more programming tutorials, please visit: CodeBilby.com

Top comments (2)

Collapse
 
alexmustiere profile image
Alex Mustiere

Ever heard of fetch ?

Collapse
 
yanyy profile image
Yongyao Yan

Thank you for your comment.
I will add this part.