In this article, we are going to look at the readyState property in more detail. When a request is sent to a web server, the server processes the request and sends data back to the browser. Before the browser takes action on the response, you want to make sure that the browser has finished receiving the response from a valid page on a web server.

We depend on the onreadystatechange event which is triggered every time the readyState changes. The readyState property contains the status of the XMLHttpRequest. We simply need to check the readyState value and status prior to taking action on the data that was received.

HTML Example

;

XMLHTTPRequest Properties

readyState Status

  • 0 – request not initialized1 – server connection established2 – request received3 – processing request4 – request completed and response is ready

To ensure that we do not take action on the data that is received from the web server until it has been completed, we simply check the status of the readyState property when the onreadystatechange event changes. When the readyState value is 4 and status value is 200, the response is ready.

xhr.onreadystatechange = function () { if (xhr.readyState == 4 && xhr.status == 200) { document.getElementById(“div1”).innerHTML = xhr.responseText; } }