Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Optimised search using Ajax and keypress

I have the following code that I want to use to search a database as a user is typing into a textbox. The code below works fine but it seems a little inefficient, as if a user is typing really fast. I am potentially doing many more searches than necessary. So if a user is typing in "sailing", I am searching on "sail", "saili", "sailin", and "sailing".

I wanted to see if there was a way to detect any particular time between keypresses so only search if user stops typing for 500 milliseconds or something like this.

Is there a best practice for something like this?

$('#searchString').keypress(function(e) {      if (e.keyCode == 13) {          var url = '/Tracker/Search/' + $("#searchString").val();         $.get(url, function(data) {             $('div#results').html(data);             $('#results').show();         });     }     else {          var existingString = $("#searchString").val();         if (existingString.length > 2) {             var url = '/Tracker/Search/' + existingString;             $.get(url, function(data) {                 $('div#results').html(data);                 $('#results').show();             });         }     } 
like image 295
leora Avatar asked Jun 12 '10 12:06

leora


1 Answers

You can do something like this:

$('#searchString').keyup(function(e) {     clearTimeout($.data(this, 'timer'));     if (e.keyCode == 13)       search(true);     else       $(this).data('timer', setTimeout(search, 500)); }); function search(force) {     var existingString = $("#searchString").val();     if (!force && existingString.length < 3) return; //wasn't enter, not > 2 char     $.get('/Tracker/Search/' + existingString, function(data) {         $('div#results').html(data);         $('#results').show();     }); } 

What this does is perform a search (on keyup, better than keypress for these situations) after 500ms by storing a timer on the #searchString element's .data() collection. Every keyup it clears that timer, and if the key was enter, searches immediately, if it wasn't sets a another 500ms timeout before auto-searching.

like image 83
Nick Craver Avatar answered Sep 24 '22 14:09

Nick Craver