Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How do you solve the "lag" problem of a live search?

Tags:

jquery

search

hi i am implementing a live search (=search as you type) feature in my webapp. currently i am using the keyup event to send the search request via ajax post e.g.

$('#SearchField').keyup(function(e) {
        $.post(
           ...
        );
});

but this leads to some kind of lag problem, in some cases when i search, for example after "problem", the response for "pro" shows up way after the response for "problem" and overwrites the correct search result with a way to big result.

what would be a good approach to combat this behavior?

tia

like image 604
marc.d Avatar asked Feb 19 '10 14:02

marc.d


1 Answers

you can abort previous request

var xhr = null;
$('#SearchField').keyup(function(e) {
  if (xhr !== null) xhr.abort ();
  xhr = $.post(
    ...
  );
});

or set assign id to each request. when a request complete, if a greater id already come back, ignore the answer. otherwise, store the id.

like image 147
Mathieu Avatar answered Oct 20 '22 01:10

Mathieu