Request in AJAX:

In AJAX there are only two types of requests synchronous and asynchronous. The XMLHttpRequest object is able to handle only these two requests within the page if it is required.

There are two behavior one is “true” and another one is “false” and it is controlled by the third parameter of open method. The “true” behavior indicates an asynchronous request and “false” behavior indicates synchronous request.

Example:

For asynchronous request:

xmlhttp.open(“GET”, “report_data.xml”, true);

For synchronous request:

xmlhttp.open(“GET”, “report_data.xml”, false);

Note:

If you not provide any value for request than by default value is “true”.

Difference between Asynchronous and Synchronous Request:

The main difference between these two requests is that, the asynchronous request will not block the web page and user can progress to interact with another part of the web page, during the request is processing on server and the synchronous request is just opposite of asynchronous request it means it will block the web page and user can not interact with any other part of the web page.

So I will suggest you to always use asynchronous AJAX request because synchronous request makes the browser unresponsive so that the user will not capable to use web page.

Now then the question is that “where synchronous request should be used?”. Synchronous request should be used in rare cases for example, if you are embedding any new JavaScript file on the client using AJAX and then referring objects from that JavaScript. Then the fetching of this new JavaScript file should be inserted through synchronous AJAX request.

Example:

Asynchronous AJAX request:

var request = new XMLHttpRequest();

request.open(‘GET’, ‘report_data.xml ‘, true);  //”true” makes the request asynchronous

request.onreadystatechange = function() {

if (request.readyState == 4) {

if (request.status == 200)

{

//request succeed

}

else

{

//request failed

}

}

};

request.send(null)

Synchronous AJAX request:

var request = new XMLHttpRequest();

request.open(‘GET’,’ report_data.xml ‘, false);  //”false” makes the request synchronous

request.send(null);

if(request.status === 200)

{

//request successful; handle the response

}

else

{

//Request failed; Show error message

}

Note:

In above example we used onreadystatechange it is nothing but it’s an event registered with XMLHttpRequest object and we will learn about it in our next topic.

Leave a Reply

Your email address will not be published. Required fields are marked *