Easy Tutorial
❮ Ajax Example Home ❯

AJAX - onreadystatechange Event


onreadystatechange Event

When a request is sent to the server, we need to perform some tasks based on the response.

The onreadystatechange event is triggered every time the readyState changes.

The readyState property holds the status information of the XMLHttpRequest.

Here are three important properties of the XMLHttpRequest object:

Property Description
onreadystatechange Stores a function (or the name of a function) that is called whenever the readyState attribute changes.
readyState Holds the status of the XMLHttpRequest. Changes from 0 to 4. 0: Request not initialized<br>1: Server connection established<br>2: Request received<br>3: Processing request<br>4: Request finished and response is ready
status 200: "OK"<br>404: Page not found

In the onreadystatechange event, we specify the tasks to be performed when the server response is ready to be processed.

When readyState is 4 and status is 200, the response is ready:

Example

Note: The onreadystatechange event is triggered 4 times (0 - 4), corresponding to each change in readyState: 0-1, 1-2, 2-3, 3-4.


Using Callback Functions

A callback function is a function passed as a parameter to another function.

If your website has multiple AJAX tasks, you should write a standard function to create an XMLHttpRequest object and call this function for each AJAX task.

This function call should include the URL and the tasks to be performed when the onreadystatechange event occurs (which may vary with each call):

Example

function myFunction()
{
    loadXMLDoc("/try/ajax/ajax_info.txt", function()
    {
        if (xmlhttp.readyState == 4 && xmlhttp.status == 200)
        {
            document.getElementById("myDiv").innerHTML = xmlhttp.responseText;
        }
    });
}
❮ Ajax Example Home ❯