What happens if I send some ajax request, and immediately change the page (say follow some link) before the request returns? I mean I suppose the XHR object sends a request to the website, but it is removed (since the page is changed) before the response is retrieved, so where should the response be sent to?
I am asking this question because I am having a strange problem with my website. I have a page that loads posts from the data store via an Ajax request. If before the load is complete I click on a link, I get the onerror of jQuery.ajax called! Not sure why that happens.
EDIT: This is my call to ajax. In the normal case, the success callback gets called. But when I click on a link, the error callback gets called! I am thinking about something, could it be because the data should be formatted as JSON, but the request is cut in the middle, so the data is considered invalid causing jQuery to call the error callback?! But then why the requests get cut in the middle?
$.ajax({
type: (args.rel == "async" || args.rel == "dialog") ? "GET" : "POST",
url: href,
dataType: "json",
data: args.data ? args.data:{}, // send {} to ensure Content-Length header
success: function(data){
if (context) context.removeClass("ajax_wait");
if (args.hideonwait) $(args.hideonwait).show();
if (args.showonwait) $(args.showonwait).hide();
if (spinner) remove_spinner(context, spinner);
handle_response(args, context, target, data);
},
error: function(xhr, status, errorThrown){
if (context) context.removeClass("ajax_wait");
if (args.hideonwait) $(args.hideonwait).show();
if (args.showonwait) $(args.showonwait).hide();
if (spinner) remove_spinner(context, spinner);
ajax_error(args, context,
status + "-" + xhr.status,
errorThrown ? errorThrown : xhr.responseText);
}
});
The trick is to check the response headers in the XMLHttpRequest object. If there are no response headers (null or empty string, depending on the browser), the server did not respond yet. That means the user aborted.
$.ajax({
url: "url-to-go-here",
success: function() {
},
error: function(xhr, textStatus, errorThrown) {
if(!isUserAborted(xhr)) {
console.log("Ajax Error")
}
}
});
function isUserAborted(xhr) {
return !xhr.getAllResponseHeaders();
}
Source
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