views:

32

answers:

1

Hi,

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

+2  A: 

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: http://stackoverflow.com/questions/446594/kill-ajax-requests-using-javascript-using-jquery

Bootnote: "lastRequest" sounds very villainous.

SimpleCoder
Hehe. Thanks for your quick reply. Your answer makes sense. I did look at the debouncing library. It worked as expected :)
punit
Sure, you're welcome
SimpleCoder