Search Facebook Style AJAX

I created a Facebook style ajax style for my site where, when you enter it, you will get the results in a good list below your search.

$("#s").keyup(function() { var searchbox = $(this).val(); var dataString = 's='+ searchbox; if(searchbox!='') { $.ajax({ type: "POST", url: "/livesearch.php", data: dataString, cache: false, success: function(html){ $("#display").html(html).show(); } }); } else {return false; } }); $("body").click(function() { $("#display").hide(); }); 

The problem with this is that it is a bit inefficient as the user types in a word like “football”. This will make 8 requests to the server. What would be a more efficient way to do this? Ideally, I think it should keep the request for 1 second before doing a search, not an instant keyboard. but not 100% sure how to do it ...

+6
javascript jquery ajax
source share
3 answers

The method you are referring to is called "Debouncing"

Usually I have the "Debounce" function at the bottom of all my scripts.

 var debounce=function(func, threshold, execAsap) { var timeout; return function debounced () { var obj = this, args = arguments; function delayed () { if (!execAsap) func.apply(obj, args); timeout = null; }; if (timeout) clearTimeout(timeout); else if (execAsap) func.apply(obj, args); timeout = setTimeout(delayed, threshold || 100); }; }; 

And then whenever I do something that can benefit from a debut, I can use it in general

So your code will be rewritten as

 $("#s").keyup(debounce(function() { var searchbox = $(this).val(); var dataString = 's='+ searchbox; if(searchbox!='') { $.ajax({ type: "POST", url: "/livesearch.php", data: dataString, cache: false, success: function(html){ $("#display").html(html).show(); } }); } else {return false; } } ,350 /*determines the delay in ms*/ ,false /*should it execute on first keyup event, or delay the first event until the value in ms specified above*/ )); 
+10
source share

Another option is to start the search after 2/3 characters. Waiting for 1 second before making each request does not look very good. Also try sending very little data back to the server, which can also speed up the request and response.

+2
source share

You may have a JSON object that sits somewhere and searches for it, instead of looking for the database several times. It won’t bring too much canopy unless it’s a list of 1000 friends or something else.

+2
source share

All Articles