Question

I am building a live search for a website that will return results based on what the user types. I only want the request to be sent when the user has finished typing.

I have tried a few implementations using timers and even the debounce method from underscore.js but I always seem to be getting a similar result.

While I am typing, the request is delayed until I have finished typing. But then it seems to fire all the inputs as if they were queued. For example, if I type in "bikes" the results come back like:

b

bi

bik

bikes

As such, you get a stream of results for the search.

This is my current implementation using underscore js

$('#search_term').on('keyup', _.debounce(function (e) {

       $.ajax({
            type: "GET",
             url: "quicksearch.php",
            data: { search_term:$('#search_term').val()},
            success: function(msg){
              $('#quick_search_results').html(msg).slideDown();
            }
    });

}, 100));

Anyone have any ideas?

Was it helpful?

Solution

Maybe your users cannot type fast enough. Set the wait parameter of the _.debounce function to be longer than the 100ms in your example: (see specs: _.debounce(function, wait, [immediate]).

$('#search_term').on('keyup', _.debounce(function (e) {
   $.ajax({
        type: "GET",
        url: "quicksearch.php",
        data: { search_term:$('#search_term').val()},
        success: function(msg){$('#quick_search_results').html(msg).slideDown();}
   });
}, 300)); // < try 300 rather than 100

OTHER TIPS

you can do this by setting a setTimeout to make an ajax call on every change that occurs on input after passing a specific time but don't forget to kill the previous calls.

var debounce;
$('#input').on('input', function (e) {
    clearTimeout(debounce);
    debounce = setTimeout( 
      function () { 
        searchText(e.target.value) 
      }, 1000
    );
});

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top