In this tutorial you will learn about the AJAX readyState and its application with practical example.
Whenever XMLHttpRequest object makes request to server this request goes through a cycle till server returns the response, XMLHttpRequest object have option to keep track of this request/readyState cycle using onreadystatechange property which triggers or fires a event as readyState changes.
The readyState property defines the current state of the XMLHttpRequest object.
Property | Description |
---|---|
onreadystatechange | It defines an event handler for an event that fires at every state change. |
readyState | Returns the status of the XMLHttpRequest. possible values for the readyState propery: 0: The request is not initialized 1: Server connection has been set up 2: The request has been sent 3: The request is in process 4: The request is completed and response is ready |
status | 200: “OK” 404: Page not found |
statusText | Returns the status as a string (e.g. “Not Found” or “OK”). |
1 2 3 4 5 6 7 8 9 |
<script language="javascript"> xmlhttp.onreadystatechange=function() { if (xmlhttp.readyState==4 && xmlhttp.status==200) { document.getElementById("result_div").innerHTML=xmlhttp.responseText; } } </script> |
Using a Callback Function in AJAX
1 2 3 4 5 6 7 8 9 10 11 12 |
<script language="javascript"> xmlhttp.onreadystatechange=callback_fun; function callback_fun() { if (xmlhttp.readyState==4 && xmlhttp.status==200) { document.getElementById("result_div").innerHTML=xmlhttp.responseText; } } </script> |