3

I have this simple piece of code:

$(document).on("input", "#addFoodSearch", function(event){
   var search = $(this).val();
   $.ajax({ url: "/ajax/search-food.php", type: 'GET', data: { 'search' : search }, dataType: 'json' }).done(
      function(data){
         if (data[0] == 'success'){
            $('#add-food-area').html(data[1]);
            $('#add-food-area').fadeIn();
         }
      }
   );
});

What I want to do is to cancel a previous $.ajax request, if any is running, in case the user types too fast. I need only the latest request to pass, not the whole sequence of them.

How can I do this?

Frantisek
  • 7,485
  • 15
  • 59
  • 102

2 Answers2

25

Store the jqXHR object in a variable and abort it each time.

var jqxhr = {abort: function () {}};
$(document).on("input", "#addFoodSearch", function(event){
    var search = $(this).val();
    jqxhr.abort();
    jqxhr = $.ajax(...
Explosion Pills
  • 188,624
  • 52
  • 326
  • 405
7

You'd need to store a reference to the AJAX request in progress, then call the abort() method on it;

var ajax;

$(document).on("input", "#addFoodSearch", function(event){
   var search = $(this).val();

   if (ajax) {
       ajax.abort();
   }

   ajax = $.ajax({ url: "/ajax/search-food.php", type: 'GET', data: { 'search' : search }, dataType: 'json' }).done(
      function(data){
         if (data[0] == 'success'){
            $('#add-food-area').html(data[1]);
            $('#add-food-area').fadeIn();
         }
      }
   ).always(function () {
       ajax = undefined;
   });
});

... although note that cancelling an AJAX request doesn't always prevent the request from being completed on the server.

Matt
  • 74,352
  • 26
  • 153
  • 180
  • What does the ``.always`` part do? – Frantisek May 25 '13 at 15:27
  • @RichardRodriguez: See http://api.jquery.com/deferred.always/. In our case, it clears the "ajax" variable whether the AJAX request fails or succeeds, so that we don't "abort()" requests that have already completed. – Matt May 25 '13 at 15:28