views:

228

answers:

3

Hi guys, I have a search textbox where upon keppress an ajax call is made to return search results for the inputted text. The thing is that this results in an Ajax call being made for like every single keypress - so if I wish to type in lets say airport

I get 7 ajax requests each searching for a, ai, air, airp, airpo, airpor, airport respectively - however the problem is that they might all start one after the other but don't necessarily end in the same order so more often than not I recieve results in wrong order i.e I might have written airport and recieved the result for airport only to recieve the result for airpo later on...

How do I handle this in JQuery here?

============================== EDIT

There is a timer delay of 3 seconds - but the issue is in ensuring that when one Ajax request is made, another Request when made cancels out the previous request and so forth.. how could I do it in code?

+1  A: 

Sending a lookup request at every keystroke is generally a bad idea - I'd suggest instead that you send at short intervals (ie. send the textbox value every 3 seconds or so).

Further, to prevent the asynchronous returns, you could have a flag to keep track of a request's state, so that only 1 can be active at any one time (eg. set on send, cleared on return). This would effectively render your lookups synchronous.


EDIT: Added sample code

var req = null;

function sendRequest (text)
{
 // Check for pending request & cancel it
 if (req) req.abort ();

 req = $.ajax ({
  // various options..
  success: function (data)
  {
   // Process data
   ...
   // reset request
   req = null;
  }
 });
}
K Prime
There is a timer delay of 3 seconds - but the issue is in ensuring that when one Ajax request is made another Request when made cancels out the previous request and so forth.. how could I do it in code
Ali
You can use the abort() method of the XHRR object (http://www.w3.org/TR/XMLHttpRequest/#the-abort-method), as pointed out by Joel
K Prime
+1  A: 

You can cancel AJAX requests:

var x = $.ajax({
    ...
});

x.abort()

So if you want to send a new request before the previous one has returned, abort() the first one.

Joel L
I'm actually using the getJSON object - it doesn't seem to be working :(
Ali
A: 

/* Fire the ajax call on a delay - use this in conjunction with the abort() code above */

var typeDelay = function(){
    var timer = 0;
    return function(callback, ms){
        clearTimeout (timer);
        timer = setTimeout(callback, ms);
    }  
}();

$("#searchField").keypress(function(){

 typeDelay(function(){
   // your ajax search here, with a 300 ms delay...
 }, 300);

});
Mike Vysocka
The jQuery autocomplete plugin does use a delay much in this same fashion. Also.. the jQuery plugin http://plugins.jquery.com/project/ajaxqueue may help w/ your desire for synchronous ajax.
Famous Nerd