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
<!DOCTYPE html>
<html>
<head>
<script type="text/javascript">
function loadAjax() {
var xhr = false;
if (window.XMLHttpRequest) {
// IE7+, Firefox, Chrome, Opera, Safari
xhr = new XMLHttpRequest();
}
else {
// IE5/IE6
xhr = new ActiveXObject("Microsoft.XMLHTTP");
}
if (xhr) {
xhr.onreadystatechange = function () {
if (xhr.readyState == 4 && xhr.status == 200) {
document.getElementById("div1").innerHTML = xhr.responseText;
}
}
xhr.open("GET", "/demo/ajax_load.txt", true);
xhr.send(null);
}
}
</script>
</head>
<body>
<img id="img1" onclick="loadAjax()" src="go.png" /> ;
<div id="div1"> <!-- Some Content --> </div>
</body>
</html>
XMLHTTPRequest Properties
Property | Description |
---|---|
onreadystatechange | Function to be called when the readyState property changes |
readyState | Holds the status of the XMLHttpRequest . Values from 0 – 4 |
status | Returns the status-number. 200 , 404 |
statusText | Returns the status-text: Ok , Not Found |
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;
}
}