Open In App

What are the different stages and processes in AJAX ready states ?

Last Updated : 05 Sep, 2022
Improve
Improve
Like Article
Like
Save
Share
Report

In this article, we will see the different stages & processes involved in AJAX-ready states, along with knowing their importance & basic usage through the illustrations. Asynchronous JavaScript and XML(AJAX) can be used to communicate with the server without reloading the web page, so it helps in a better user experience. For interactivity with the servers, the XMLHTTPRequest objects can be used that perform the required AJAX operations & these are the browser-level APIs. The server and client requests are taken care of by Javascript. 

The readyState is an XMLHTTPRequest property that holds or can return the status of the XMLHTTPRequest clients that are currently present in it. In simple words, a request will be made to the server using the XMLHttpRequest object, which undergoes a cycle of changes & in turn, returns the response. The XMLHttpRequest keeps track of the request made with the help of readyState only, which defines the current state of the corresponding XMLHttpRequest object. The “onreadystatechange” property helps in triggering changes in the readyState. While handling the request, there are 4 different ready states that are possible.

Different AJAX readyStates:

  • When a request is sent, while reaching the server, there are many possibilities of the request getting broken. If it is not broken and the connection is successful means the status will become 1
  • When the request is received in the server, readystate status is changed to 2
  • While processing the request, the status is changed to 3.
  • When the request is finished, the status is changed to 4.

Different stages and processes in AJAX-ready states:

States

readyState Values

Explanation

UNSENT

0

The request has not been initialized yet. So initially readyState is 0.

OPENED

1

When an open() method is called, the connection is getting established, and hence the status changes to 1.

HEADERS_RECEIVED

2

When the send() method is called, the request is received, and hence the status changes to 2 & the headers and status will be available accordingly.

LOADING

3

During the time of processing the request, the downloading will be performed & the responseText carries the partial data & the status will change to 3.

DONE

4

When the request is finished processing and it is about to deliver the response, then the status changes to 4.

During the readystate 4, we need to check the status of the request object, i.e., when the status code is 200, we will get a successful response.

Different StatusCode description (Once the ready state has come to 4):

StatusCode

Explanation

200

OK. The response availability will be perfect and we can receive the whole output by using responseText

201

A request is succeeded and a new resource is created.

202-298

For each and every status code, there are changes of behavior like No Content, Partial Content, etc.,

We will understand all these concepts through the examples.

Example 1: In this example, we assume that we are going to retrieve a document that is available on a server, which may be an image or any text document, but will only be available on the same server. If the file got misplaced or corrupted, accidentally, then we will get a different readystate and we will not get a response, as well.

Here, we will try to open the “readyStatedetails.jsp” file, which will be available in the same location where ‘readyStateExample.html‘ is present. If this file got misplaced or corrupted accidentally, in that case, it is not available on the server. 

readyStateExample.html:

HTML




<!DOCTYPE html>
<html>
 
<head>
    <title>
        Different stages & processes
        in AJAX readyStates
    </title>
</head>
 
<body style="text-align: center;">
    <div id="gfgdemo">
        <h1 style="color: green;">
            GeeksforGeeks
        </h1>
         
        <h3>onreadystatechange Example Demo</h3>
         
        <button type="button" onclick="loadDoc()">
            Retrieve a document
        </button>
    </div>
 
    <script>
        function loadDoc() {
            const xmlhttp = new XMLHttpRequest();
            xmlhttp.onreadystatechange = function () {
                switch (this.readyState) {
                    case 1:
                        alert(
                            "After establishing connection,"
                            + "readyState has changed to = "
                            + this.readyState);
                        break;
                    case 2:
                        // If send method is not called,
                        //readyState cannot become 2
                        alert("send method is called," +
                            "readyState has changed to = "
                            + this.readyState);
                        break;
                    case 3:
                        // If send method is there, from readyState 2,
                        // It will get changed to 3
                        alert(
                            "Processing the request,"
                            + " readyState has changed to = "
                            + this.readyState);
                    case 4:
                        // Only when readyState = 4,
                        // we will check for status
                        alert("Request has finished processing,"
                            + "readyState has changed to= "
                            + this.readyState
                            + " and let us check for responses");
                        alert("As readyState is reached 4,"
                            + " current status is "
                            + this.status);
                        switch (this.status) {
                            case 200:
                                document.getElementById("gfgdemo")
                                    .innerHTML = this.responseText;
                                break;
                            case 404:
                                alert("Requested readyStatedetails.jsp"
                                    + " file is not available in the server");
                                document.getElementById("gfgdemo").innerHTML =
                                    "Requested readyStatedetails.jsp file is" +
                                    "not available in the server";
                                break;
                            default:
                                // In case of different status, if the
                                // expected resource is not available
                                // in the server/IO issues etc.,
                                alert(
                                    " Unexpected error occurred.."
                                    + this.status
                                    + ".\nPlease try after sometime");
                        }
                        break;
                } // End of readyState
            };
 
            // We are trying to open readyStatedetails.jsp
            // that is available in the same server
            // where this html file present
            xmlhttp.open("GET", "readyStatedetails.jsp");
            xmlhttp.send();
        }
    </script>
</body>
 
</html>


Explanation: When the connection is open, the readyState gets changed to 1. When send() method is called, the readyState gets changed to 2 and starts to process the request and the readyState gets changed to 3, and tries to complete the request and starts to provide the response via readyState 4. At that time, if the requested file is not available on the same server, even though readyState has gone to 4, then its status cannot be 200 (OK) which means, the requested operation is not fully completed and hence could not possibly produce the response.

Note: We will be assuming that we do not have the readyStatedetails.jsp file in the server.

Output: As the requested file is not on the server, the status has become 404 which means it is not available on the server.

 

Example 2: In this example, we assume the readyStatedetails.jsp is available in the server. Here, we will be using the same readyStateExample.html file to observe the changes that appear.

readyStatedetails.jsp:

HTML




<!DOCTYPE html>
<html>
 
<head>
    <title>
         JSP page rendering of Ready state values
    </title>
</head>
 
<body style="text-align:center">
    <h1>Ready State Values</h1>
    <table border="1" color="green">
        <tr>
            <th>0-Request Not Initialized</th>
        </tr>
        <tr>
            <th>
                1-When an open method is called,
                connection is getting established
                and hence the status changes to 1
            </th>
        </tr>
        <tr>
            <th>
                2-When a send method is called,
                request is received and hence
                the status changes to 2
            </th>
        </tr>
        <tr>
            <th>
                3-During the time of processing
                the request, the status changes
                to 3
            </th>
        </tr>
        <tr>
            <th>
                4-When the request is finished
                processing and it is about to
                deliver the response, then the
                status changes to 4
            </th>
        </tr>
    </table>
</body>
</html>


Output:

 

Conclusion: The readyState values are really helpful to know about the output of a requested resource or output of an ajax call. If we get a response, then the request might have been completed with a readyState value of 4 and a response of 200 (OK), and hence in the output, we can see the proper response.  We can handle the issues by means of handling exceptions as well.



Like Article
Suggest improvement
Previous
Next
Share your thoughts in the comments

Similar Reads