I have been having a few issues with ajax error function getting called while the script is taking a while to load. But I was able to fix it by adding async: false
.
E.g:
$.ajax({
type: 'POST',
url: REQUEST_URL,
async: false,
data: {
'id': id
},
dataType: 'json',
success: function(output) {
// success
},
error: function() {
alert('Error, please refresh the page');
}
});
When reading the docs it says:
By default, all requests are sent asynchronously (i.e. this is set to true by default). If you need synchronous requests, set this option to false. Cross-domain requests and dataType: "jsonp" requests do not support synchronous operation. Note that synchronous requests may temporarily lock the browser, disabling any actions while the request is active. As of jQuery 1.8, the use of async: false with jqXHR ($.Deferred) is deprecated; you must use the complete/success/error callbacks.
Q) What does the last part mean about jqXHR ($.Deferred)? Does this effect my script?
As of jQuery 1.8, the use of async: false with jqXHR ( $.Deferred ) is deprecated; you must use the success/error/complete callback options instead of the corresponding methods of the jqXHR object such as jqXHR.done() .
Synchronous XMLHttpRequest (async = false) is not recommended because the JavaScript will stop executing until the server response is ready. If the server is busy or slow, the application will hang or stop.
It does not affect your script.
It means that, when performing synchronous AJAX requests, one should not use the deferred API exposed by the object returned by $.ajax()
(like done() or fail() for instance), but rely on the complete
and error
handlers instead.
In other words, your code already uses the right pattern. You would have to modify it if it used deferred operations like:
// Do not write this code.
$.ajax({
type: 'POST',
url: REQUEST_URL,
async: false, // <-- Synchronous request.
data: {
'id': id
},
dataType: 'json'
}).done(function(output) { // <-- Use of deferred method.
// success
}).fail(function() { // <-- There also.
alert('Error, please refresh the page');
});
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With