XMLHttpRequest readystate values

When we are using XMLHttpRequest object it is the readystate value which is very important. Depending upon the value of this property we decide what action to perform.

readystate property can have one of the following value

  • 0
  • 1
  • 2
  • 3
  • 4

If we have only created the object but have not yet opened the connection its value is 0. As soon as you open a connection on this object its value is changed to 1. When you have made a request using its send method readystate changes to 2. When the server starts sending data and the object is receiving data its value becomes 3 and implies id is receiving data but has not completely received the data. When all the data is received its state changes to 4.

Now generally jQuery is used everywhere which takes care of these minute details and we need not to worry about readystate.

When we are designing an application in ajax we assign onreadystatechange property of the XMLHttpRequest object to the event handler which will be processing the received server data. In that event handler we need to check this readystate value as this function will be called each time the state changes as stated above. Depending on the state we perform the required action.

var client = new XMLHttpRequest();
client.onreadystatechange = testhandler;
client.open("GET", "test.xml");
function testhandler()
    if (client.readystate==4)
        //do the required stuff

After statement 1 readystate has a value 0, after statement 3 it has value 1, after statement 4 it has a value 2. In the function testhandler we are checking the readystate value to see if the response has been received completely by comparing it to 4.

Leave a Reply

Your email address will not be published. Required fields are marked *

This site uses Akismet to reduce spam. Learn how your comment data is processed.