Monitoring Server Status

The XMLHTTPRequest object contains mechanisms by which we can stay informed of the progress of our Ajax request and determine when the information returned by the server is ready to use in our application.

Let's now have a look at the relevant properties.

The readyState Property

The readyState property of the XMLHTTPRequest object gives you information from the server about the current state of a request you have made. This property is monitored by the onreadystatechange property, and changes in the value of readyState cause onreadystatechange to become true and therefore cause the appropriate function (responseAjax() in our example) to be executed.

Tip

 

The function called on completion of the server request is normally referred to as the callback function.

 

readyState can take the following values:

0 = uninitialized
1 = loading
2 = loaded
3 = interactive
4 = completed

When a server request is first made, the value of readyState is set to zero, meaning uninitialized.

As the server request progresses, data begins to be loaded by the server into the XMLHTTPRequest object, and the value of the readyState property changes accordingly, moving to 1 and then 2.

An object readyState value of 3, interactive, indicates that the object is sufficiently progressed so that certain interactivity with it is possible, though the process is not yet fully complete.

When the server request has completed fully and the object is available for further processing, the value of readyState changes finally to 4.

Tip

 

Not all of the possible values may exist for any given object. The object may "skip" certain states if they bear no relevance to the object's content type.

 

In most practical cases, you should look for the readyState property to achieve a value of 4, at which point you can be assured that the server has finished its task and the XMLHTTPRequest object is ready for use.

Server Response Status Codes

In addition to the readyState property, you have a further means to check that an asynchronous request has executed correctly: the HTTP server response status code.

HTTP responses were discussed in Lesson 3, "Sending Requests Using HTTP." If you refer to Table 3.1 you'll see that a response status code of 200 corresponds to an OK message from the server.

We'll see how to test for this as we further develop our callback function.