AJAX - onreadystatechangeEvent


onreadystatechange Event

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

Whenever readyState changes, the onreadystatechange event is triggered.

The readyState property holds the status information of the XMLHttpRequest.

Below are the three important properties of the XMLHttpRequest object:

Property Description
onreadystatechange Stores a function (or the name of a function) to be called whenever the readyState property changes.
readyState

Holds the status of the XMLHttpRequest. Changes from 0 to 4.

  • 0: Request not initialized
  • 1: Server connection established
  • 2: Request received
  • 3: Processing request
  • 4: Request finished and response is ready
status 200: "OK"
404: Page not found

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

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

Example

xmlhttp.onreadystatechange=function() { if (xmlhttp.readyState==4 && xmlhttp.status==200) { document.getElementById("myDiv").innerHTML=xmlhttp.responseText; } }

Try it Yourself »

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


Using a Callback Function

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

If your website has multiple AJAX tasks, you should write astandardfunction for creating XMLHttpRequest objects, and call that function for each AJAX task.

The function call should contain the URL and the task to be executed when the onreadystatechange event occurs (the task may differ 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; } }); }

Try it Yourself »
Other Extensions