In this article I will explain how to resolve the following error occurring 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/.
Error
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.
Cause
The above error occurs when jQuery AJAX Call is used with async setting set to false. 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.
Solution
The solution to the above problem is to set async setting of the jQuery AJAX function to true as 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.