Runoob Tutorial ArchiveEnglish

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.

  • 0: Request not initialized
  • 1: Connection established with the server
  • 2: Request received
  • 3: Request processing
  • 4: Request completed and response is ready
  • | | status | 200: "OK" 404: Page not found |

    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 »