AJAX – onreadystatechange event
AJAX - onreadystatechange event
onreadystatechange event
When the request is sent to the server, we need to perform some tasks based on the response.
The onreadystatechange event is triggered whenever readyState changes.
The readyState property stores the status information of XMLHttpRequest.
Below are three important properties of the XMLHttpRequest object:
| Property | Description |
|---|---|
| onreadystatechange | A storage function (or function name) that is called whenever the readyState property changes. |
| readyState |
Stores the state of the XMLHttpRequest. Changes from 0 to 4. |
In the onreadystatechange event, we define the task to be executed when the server response is ready to be processed.
When readyState is 4 and the status is 200, it indicates that the response is ready:
instance
xmlhttp
.
onreadystatechange
=
function
(
)
{
if
(
xmlhttp
.
readyState
==
4
&&
xmlhttp
.
status
==
200
)
{
document
.
getElementById
(
"
myDiv
"
)
.
innerHTML
=
xmlhttp
.
responseText
;
}
}
Try it »
Note:The onreadystatechange event is triggered 4 times (0 - 4), corresponding to each change in readyState: 0-1, 1-2, 2-3, and 3-4.
Use a callback function
A callback function is a function passed as an argument to another function.
If your website has multiple AJAX tasks, you should write astandardfunction for creating XMLHttpRequest objects and call this function for each AJAX task.
This function call should include the URL and the task to be executed when the onreadystatechange event occurs (the task may be different for each call):
instance
function
myFunction
(
)
{
loadXMLDoc
(
"
/try/ajax/ajax_info.txt
"
,
function
(
)
{
if
(
xmlhttp
.
readyState
==
4
&&
xmlhttp
.
status
==
200
)
{
document
.
getElementById
(
"
myDiv
"
)
.
innerHTML
=
xmlhttp
.
responseText
;
}
}
)
;
}
Try it »