Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Change page in the middle of Ajax request

Tags:

jquery

ajax

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);
  }
});
like image 608
Rafid Avatar asked Aug 02 '11 10:08

Rafid


1 Answers

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

like image 142
Yasser Shaikh Avatar answered Oct 06 '22 09:10

Yasser Shaikh