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?
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 thecompleteanderrorhandlers instead.In other words, your code already uses the right pattern. You would have to modify it if it used deferred operations like: