Effective AutoSuggest with jQuery?

I am working on a jQuery AutoSuggest plugin inspired by an Apple spotlight.

Here is the generic code:

$(document).ready(function() { 
$('#q').bind('keyup', function() {

    if( $(this).val().length == 0) {
        // Hide the q-suggestions box
        $('#q-suggestions').fadeOut();
    } else {
        // Show the AJAX Spinner
        $("#q").css("background-image","url(/images/ajax-loader.gif)");

        $.ajax({
            url: '/search/spotlight/',
            data: {"q": $(this).val()},
            success: function(data) {
                $('#q-suggestions').fadeIn(); // Show the q-suggestions box
                $('#q-suggestions').html(data); // Fill the q-suggestions box

                // Hide the AJAX Spinner
                $("#q").css("background-image","url(/images/icon-search.gif)");

            }
        });
    }
});

The problem that I want to solve well and elegantly does not kill the rank. At the moment, the code above gets to the server every time you enter the key, and did not wait for the text to complete. What is the best way to solve this problem? A. Kill the previous AJAX request? B. What type of caching is AJAX? C. Adding some type of delay to send .AJAX () when a person stopped typing in 300 ms or so?

+5
source share
4 answers

Ben Alman Throttle Debounce

"" , .

, , debouncing

var qinput = $('#q').bind('keyup', $.debounce( 250, function() {

    if( $(this).val().length == 0) {
        // Hide the q-suggestions box
        $('#q-suggestions').fadeOut();
    } else {
        // Show the AJAX Spinner
        qinput.addClass('loading');

        $.ajax({
            url: '/search/spotlight/',
            data: {"q": $(this).val()},
            success: function(data) {
                $('#q-suggestions')
                    .fadeIn() // Show the q-suggestions box
                    .html(data); // Fill the q-suggestions box

                // Hide the AJAX Spinner
               qinput.removeClass('loading').addClass('search');
            }
        });
    }
}));

CSS

.loading{
    background: url('/images/ajax-loader.gif');
}
.search{
    background: url('/images/icon-search.gif');
}

, css- background-image addClass/removeClass. css css .

+9

C. , , (200?) . , , . , .

; backspace, .

+2

, , !?

TOT NUMS

es.: after 3 ( mysql ) chars DB json !

, PHP , FILTERING .. .. !

btw I believe one of the best AutoSuggest is one of brandspankingnew

+2
source

There is a timeout option in the autocomplete plugin that you can set for this.

http://docs.jquery.com/Plugins/AutoComplete/autocomplete

+1
source

All Articles