Cancelling previous ajax request jquery

From what I've read the general solution to this is as follows:

var DataRequest = $.ajax({ /* ... */ });

and then DataRequest.abort() in the beforeSend ajax event. However, this results in NO requests being sent.

What I'm trying to achieve is to abort any ajax operations that are declared as DataRequest (for example), and allow only the latest request to proceed. Currently I have a button that when clicked starts a request and adds a loading spinner. If I click it many times, I just get a bunch of loading spinners filling up my page. How can I prevent this?

Here's the relevant code:

beforeSend: function() {
    $('<div class="grid"></div>')
        .attr('id', 'loading')
        .hide()
        .insertBefore('#output')
        .fadeIn();
},

success: function(data) {
    $('#loading').hide(function () {
        $(this).remove();
    });
}

Answers


Here's the pattern I use when I need to have multiple requests and only process the last:

var fooXHR, fooCounter=0;
$(...).bind( 'someEvent', function(){
  // Do the Right Thing to indicate that we don't care about the request anymore
  if (fooXHR) fooXHR.abort();

  var token = ++fooCounter;
  fooXHR = $.get( ..., function(data){
    // Even aborted XHR may cause the callback to be invoked
    if (token != fooCounter) return;

    // At this point we know that we're using the data from the latest request
  });
});

Edit: I have wrapped this functionality up in a plugin-like method call here: Can you cancel a jQuery AJAX call before it returns?


Need Your Help

Multiple spinners in ActionBar

android spinner android-spinner

I use ActionBarSherlock, in which I set the navigation mode to 'list'

About UNIX Resources Network

Original, collect and organize Developers related documents, information and materials, contains jQuery, Html, CSS, MySQL, .NET, ASP.NET, SQL, objective-c, iPhone, Ruby on Rails, C, SQL Server, Ruby, Arrays, Regex, ASP.NET MVC, WPF, XML, Ajax, DataBase, and so on.