The onreadystatechange event
When a request to a server is sent, we want to perform some actions based on the response.
The onreadystatechange event is triggered every time the readyState changes.
The readyState property holds the status of the XMLHttpRequest.
Three important properties of the XMLHttpRequest object:
Property | Description |
---|---|
onreadystatechange | Stores a function (or the name of a function) to be called automatically each time the readyState property changes |
readyState | Holds the status of the XMLHttpRequest. Changes from 0 to 4: 0: request not initialized 1: server connection established 2: request received 3: processing request 4: request finished and response is ready |
status | 200: "OK" 404: Page not found |
In the onreadystatechange event, we specify what will happen when the server response is ready to be processed.
When readyState is 4 and status is 200, the response is ready:
Example
function loadDoc() {
var xhttp = new XMLHttpRequest();
xhttp.onreadystatechange = function() {
if (xhttp.readyState == 4 && xhttp.status == 200) {
document.getElementById("demo").innerHTML = xhttp.responseText;
}
};
xhttp.open("GET", "ajax_info.txt", true);
xhttp.send();
}
Note: The onreadystatechange event is triggered five times (0-4), one time for each change in readyState.
Using a Callback Function
A callback function is a function passed as a parameter to another function.
If you have more than one AJAX task on your website, you should create ONE standard function for creating the XMLHttpRequest object, and call this for each AJAX task.
The function call should contain the URL and what to do on onreadystatechange (which is probably different for each call):
Example
function loadDoc(url, cfunc) {
var xhttp;
xhttp=new XMLHttpRequest();
xhttp.onreadystatechange = function() {
if (xhttp.readyState == 4 && xhttp.status == 200) {
cfunc(xhttp);
}
};
xhttp.open("GET", url, true);
xhttp.send();
}