YouTip LogoYouTip

Ajax Xmlhttprequest Onreadystatechange

# 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. Below are 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 for processing. When readyState equals 4 and the status is 200, it means 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), specifically during transitions: 0-1, 1-2, 2-3, and 3-4, corresponding to each change in readyState. * * * ## Using Callback Functions A callback function is a function passed as an argument to another function. If your website has multiple AJAX tasks, you should write a _standard_ function for creating the XMLHttpRequest object and call this function for each AJAX task. This function call should include the URL and the task to execute when the onreadystatechange event occurs (which 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 Β»](
← Ajax ExamplesAjax Xmlhttprequest Response β†’