Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

jQuery.ajax(): discard slow requests

Tags:

jquery

ajax

I've build a livesearch with the jQuery.ajax() method. On every keyup events it receives new result data from the server.

The problem is, when I'm typing very fast, e.g. "foobar" and the GET request of "fooba" requires more time than the "foobar" request, the results of "fooba" are shown.

To handle this with the timeout parameter is impossible, I think.

Has anyone an idea how to solve this?

like image 743
Thomas Avatar asked Jun 15 '10 17:06

Thomas


2 Answers

You can store and .abort() the last request when starting a new one, like this:

var curSearch;
$("#myInput").keyup(function() {
  if(curSearch) curSearch.abort(); //cancel previous search
  curSearch = $.ajax({ ...ajax options... }); //start a new one, save a reference
});

The $.ajax() method returns the XmlHttpRequest object, so just hang onto it, and when you start the next search, abort the previous one.

like image 137
Nick Craver Avatar answered Oct 20 '22 22:10

Nick Craver


Assign a unique, incrementing ID to each request, and only show them in incrementing order. Something like this:

var counter = 0, lastCounter = 0;
function doAjax() {
  ++counter;
  jQuery.ajax(url, function (result) {
    if (counter < lastCounter)
      return;
    lastCounter = counter;
    processResult(result);
  });
}
like image 27
Wim Avatar answered Oct 20 '22 22:10

Wim