< Ajax Tutorial

Ajax responses

← Previous Next →


AJAX Responses

The readyState property holds the status of the XMLHttpRequest.
The onreadystatechange property defines a function to be executed when the readyState changes.
The status property and the statusText property holds the status of the XMLHttpRequest object.

All these properties have already been discussed earlier. The following exmaple shows the usage of these properties:

function loadDoc() {
    var xhttp = new XMLHttpRequest();
    xhttp.onreadystatechange = function() {
        if (this.readyState == 4 && this.status == 200) {
            document.getElementById("demo").innerHTML =
            this.responseText;
       }
    };
    xhttp.open("GET", "ajax_info.txt", true);
    xhttp.send(); 
} 

If you have more than one AJAX task in a website, you should create one function for executing the XMLHttpRequest object, and one callback function for each AJAX task. The function call should contain the URL and what function to call when the response is ready.

The following example demonstrates how to do this:

loadDoc("url-1", myFunction1);

loadDoc("url-2", myFunction2);

function loadDoc(url, cFunction) {
  var xhttp;
  xhttp=new XMLHttpRequest();
  xhttp.onreadystatechange = function() {
    if (this.readyState == 4 && this.status == 200) {
      cFunction(this);
    }
 };
  xhttp.open("GET", url, true);
  xhttp.send();
}

function myFunction1(xhttp) {
  // action goes here
} 
function myFunction2(xhttp) {
  // action goes here
} 

Server Response properties are shown in the following table:

 Property Description 
 responseText  get the response data as a string
 responseXML  get the response data as XML data

Server Response Methods are shown in the following table:

 Method Description 
 getResponseHeader()  Returns specific header information from the server resource
 getAllResponseHeaders()  Returns all the header information from the server resource
← Previous Next →