Ajax XMLHttpRequest Events

We have already seen that the request made to the server is using the XMLHttpRequest object. In this tutorial we will be learning more details about the XMLHttpRequest object and its properties.

Properties of the XMLHttpRequest object :

Consider the below scenario -

  1. Request is sent to server using the XMLHttpRequest object.
  2. When request is sent to the server then some actions will be performed on the current page depending on the response that we obtain.
  3. onreadystatechange event is triggered each and every time when the status of readyState changes
  4. XMLHttpRequest holds the status of readyState property
  5. onreadystatechange event is triggered five times each time when status of readyState is changed

Three properties of the XMLHttpRequest object :

PropertyDescription
onreadystatechangeStores a function (or the name of a function) to be called automatically each time the readyState property changes
readyStateHolds 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
status200: “OK”
404: Page not found

Example of Events :

To See complete example : Click here

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

In the above code snippet, we have written two conditions inside if block. Our code will be executed when readyState of the request is 4 and request status is 200. (Refer above Table for Status)