Saturday, June 24, 2017

JavaScript: AJAX Response


Introduction

In the last post, we have learned how to send AJAX request to the server. After sending the request to the server, the server will send back a response. The response is processed using the property "XMLHttpRequest.onreadystatechange". There are more properties that we will be using to handle the response:
  • The property XMLHttpRequest.readyState
  • The property XMLHttpRequest.status
  • The property XMLHttpRequest.responseText


The property "XMLHttpRequest.readyState"

The "XMLHttpRequest.readyState" is a number that can have 5 values:
  • Request not initialized = 0.
  • Connection Established = 1.
  • Request received = 2.
  • Processing = 3.
  • Finished = 4.
The next code example can be used to show the status of the request each time the value of "XMLHttpRequest.readyState" changes.

var xmlhttpReq = new XMLHttpRequest();
xmlhttpReq.onreadystatechange = function(){
    switch (xmlhttpReq.readyState) {
        case 0:{
            console.log('Request not initialized');
            break;
        }

        case 1:{
            console.log('Connection Established');
            break;
        }

        case 2:{
            console.log('Request received');
            break;
        }

        case 3:{
            console.log('Processing');
            break;
        }
        case 4:{
            console.log('Finished');
            break;
        }
    }
}
xmlhttpReq.open('GET', '', true);
xmlhttpReq.send();



The property "XMLHttpRequest.status"

The value of this property can change at any time. It is basically a code that can be used to identify the status of the request. The value of this property can be any value that is used to identify the status of HTTP request. For example, the value 200 means OK. the value 500 means server error and so on.
If the value of "XMLHttpRequest.status" is 200 and the value of "XMLHttpRequest.readyState" is 4, then the request was successful.

var xmlhttpReq = new XMLHttpRequest();
xmlhttpReq.open('GET', '', true);
xmlhttpReq.onreadystatechange = function(){
    if(xmlhttpReq.status == 200 && xmlhttpReq.readyState == 4){
        //request succeeded
    }
}
xmlhttpReq.send();



The property "XMLHttpRequest.responceText"

This property is used to access the data that was sent by the server. It can be a simple text, A JSON object or XML document or any thing else. The following example shows how to access the value of this property.

var xmlhttpReq = new XMLHttpRequest();
xmlhttpReq.open('GET', '', true);
xmlhttpReq.onreadystatechange = function(){
    if(xmlhttpReq.status == 200 && xmlhttpReq.readyState == 4){
        //print response body
        console.log(xmlhttpReq.responseText);
    }
}
xmlhttpReq.send();

This is all what you need to know about AJAX in order to use it.

No comments:

Post a Comment

Feel free to write any thing in your mind here 😉