In this article I will explain with an example, what is the difference between Synchronous (Sync) and Asynchronous (Async) Request (Call) in AJAX.
This article will illustrate the difference between Synchronous (Sync) and Asynchronous (Async) Request (Call) in AJAX using jQuery.
jQuery Synchronous AJAX call
When async setting is set to false, a Synchronous call is made instead of an Asynchronous call.
Synchronous call is not recommended by W3C as it blocks (hangs) the page until the response is received from the server.
Example of Synchronous call
<script type="text/javascript" src="http://ajax.googleapis.com/ajax/libs/jquery/1.8.3/jquery.min.js"></script>
<script type="text/javascript">
function ShowCurrentTime() {
$.ajax({
async: false,
type: "POST",
url: "Default.aspx/GetCurrentTime",
data: '{name: "Mudassar" }',
contentType: "application/json; charset=utf-8",
dataType: "json",
success: function (response) {
alert(response.d);
}
});
}
</script>
Screenshot
You will notice that the Button is getting stuck and the browser appears to be blocked (hanged) and user cannot do anything until the call is completed.
The following error occurs during jQuery AJAX call.
Synchronous XMLHttpRequest on the main thread is deprecated because of its detrimental effects to the end user's experience. For more help http://xhr.spec.whatwg.org/.
The following screenshot displays the error logged in Mozilla FireFox console.
jQuery Asynchronous AJAX call
When the async setting of the jQuery AJAX function is set to true then a jQuery Asynchronous call is made. AJAX itself means Asynchronous JavaScript and XML and hence if you make it Synchronous by setting async setting to false, it will no longer be an AJAX call.
Example of Asynchronous call
<script type="text/javascript" src="http://ajax.googleapis.com/ajax/libs/jquery/1.8.3/jquery.min.js"></script>
<script type="text/javascript">
function ShowCurrentTime() {
$.ajax({
async: true,
type: "POST",
url: "Default.aspx/GetCurrentTime",
data: '{name: "Mudassar" }',
contentType: "application/json; charset=utf-8",
dataType: "json",
success: function (response) {
alert(response.d);
}
});
}
</script>
Screenshot
The following example does not block (hang) the page when an Asynchronous call is made.