4

I'm implementing a live search feature on my website(rails). Everytime there is a keypress, I'm submitting the form. But if the user types several characters, several search requests are sent to the server. I was wondering if there is a way to stop the previous(unprocessed) requests. I want only the last request to be successfully processed.

I know there is a abort() method which aborts an ajax request, but I no longer have control over the previous request, so I can't call abort on that. Maybe I'm doing something wrong here.

Anybody?

Thanks

Punit

Punit Rathore
  • 970
  • 1
  • 8
  • 16
  • To "cancel" a request, simply stop listening/handling *that particular requests* response; there are several ways to do this including just having a "running" callback with tags or explicit managing of 'valid' callbacks, etc. However, for a better answer, see SimpleCoder's reply. –  Sep 12 '10 at 21:45

1 Answers1

5

There is no way to stop an Ajax request using jQuery. A better way of handling this kind of thing is by "debouncing" the event: http://benalman.com/code/projects/jquery-dotimeout/examples/debouncing/ (try the first example). That way the event won't fire for every keypress; just when the user pauses for a brief period. Otherwise, you are going to end up with a lot of requests.

There is a way, however:

var lastRequest;
$("input").keypress(function(){
    if (lastRequest){
        lastRequest.abort();
        lastRequest = null;
    }
    lastRequest = $.ajax({type: "POST", url: "some.php", data: "your=data&goes=here"});
});

From: Abort Ajax requests using jQuery

Bootnote: "lastRequest" sounds very villainous.

Community
  • 1
  • 1
Chris Laplante
  • 29,338
  • 17
  • 103
  • 134
  • Hehe. Thanks for your quick reply. Your answer makes sense. I did look at the debouncing library. It worked as expected :) – Punit Rathore Sep 12 '10 at 21:55