onreadystatechange event
When a request is sent to the server, we need to perform some response-based tasks.
Whenever readyState changes, the onreadystatechange event will be triggered.
The readyState attribute stores the status information of XMLHttpRequest.
The following are three important properties of the XMLHttpRequest object:
Attributes Description
onreadystatechange Stores a function (or function name) that will be called whenever the readyState property changes.
readyState The state of XMLHttpRequest exists. Changes from 0 to 4.
0: The request is not initialized 3: Request is being processed
4: The request has been completed and the response is ready
status 200: "OK" 404: Page not found
In the onreadystatechange event, we stipulate Tasks performed when the server response is ready to be processed.
When readyState is equal to 4 and the status is 200, it means that the response is ready:
xmlhttp.onreadystatechange=function() { if (xmlhttp.readyState==4 && xmlhttp.status==200) { document.getElementById("myDiv").innerHTML=xmlhttp.responseText; } }
Note: The onreadystatechange event is triggered 5 times (0 - 4), corresponding to each change of readyState.
Using callback functions
A callback function is a function that is passed to another function in the form of parameters.
If there are multiple AJAX tasks on your website, then you should write a standard function for creating an XMLHttpRequest object and call that function for each AJAX task.
This function call should contain the URL and the task to be performed when the onreadystatechange event occurs (may be different for each call):
function myFunction() { loadXMLDoc("ajax_info.txt",function() { if (xmlhttp.readyState==4 && xmlhttp.status==200) { document.getElementById("myDiv").innerHTML=xmlhttp.responseText; } }); }