jQuery – stop an ajax call!

It’s a simple task with no simple question, although in jQuery, as I mentioned now, everything is very simple. Even this task.

In a short example we’ve a simple AJAX call with very large request.

xhr = $.ajax({
    url : 'www.example.com?some-large-call',
    success : function(responseText) {
        // some DOM manipulation
    }
});

But what if something changes the data we’d like to request with this call even before the response has come. For example I click on a category in the site but before all the data has come I’d prefer to see other category’s data.

In this case I just add some more code to the example. Actually it’s important to notice that $.ajax is returning an object that can be “aborted”.

var xhr = null;

xhr = $.ajax({
    url : 'www.example.com?some-large-call',
    success : function(responseText) {
        // some DOM manipulation
    }
});

$(document).click(function() { xhr.abort() });

As you can see this is really a mixture between working and pseudo code, so it will require a little bit more improvisation!

Leave a Reply

Your email address will not be published. Required fields are marked *

*
To prove you're a person (not a spam script), type the security word shown in the picture. Click on the picture to hear an audio file of the word.
Anti-spam image