When a request is sent to the server, we need to perform some response-based tasks.
The onreadystatechange event is triggered whenever the readyState changes.
The ReadyState attribute holds state information for XMLHttpRequest.
The following are three important properties of the XMLHttpRequest object:
onReadyStateChange
The function (or function name) is called whenever the ReadyState property is changed.
ReadyState
The state of being xmlhttprequest. Vary from 0 to 4.
- 0: Request not initialized
- 1: Server Connection established
- 2: Request received
- 3: In Request processing
- 4: The request is complete and the response is ready
Status
- $: "OK"
- 404: Page Not Found
In the onReadyStateChange event, we specify the tasks that are performed when the server responds to readiness to be processed.
When ReadyState equals 4 and the status is 200, the response is ready:
function () { if (xmlhttp.readystate = = 4 && xmlhttp.status = =) { document.getElementById ("mydiv"). InnerHTML = xmlhttp.responsetext; }}
The onReadyStateChange event is triggered 5 times (0-4), corresponding to each change of the readyState.
Using the Callback function
The callback function is a function that is passed as an argument to another function.
If you have multiple Ajax tasks on your site, you should write a standard function for creating XMLHttpRequest objects and call that function for each AJAX task.
The function call should contain the URL and the task that is performed when the onReadyStateChange event occurs (each call may be different):
function myFunction () { loadxmldoc(function () { if (xmlhttp.readystate = = 4 & & xmlhttp.status = =) { document.getElementById ("mydiv"). InnerHTML = xmlhttp.responsetext; } });}
Ajax Basics Tutorial: onReadyStateChange Events