Mohamad
Mohamad

Reputation: 35349

Throttling an ajax livesearch function

I would like to throttle the following ajax live search function I wrote.

I made it so that requests are only sent if a minimum of 2 characters are entered. I also want to throttle the ajax for a quarter of a second to give the user a chance to type what they want. I wrapped the ajax in a setTimeout function, but that didn't work.

        $('#search').keyup(function() {
            var string = $(this).val();
            if (string.length >= 2) {
                $.ajax({
                    'type': 'GET',
                    dataType: 'html',
                    'url': url,
                    'success': function(data){
                                    // show the search data
                    }
                });                                             
            } else if (string.length <= 1) {
                        // restore page content as of when it was loaded
            }
        });

Another thing I should ask, I should probably cache the results of the ajax, no?

Upvotes: 2

Views: 772

Answers (2)

Jacek Kaniuk
Jacek Kaniuk

Reputation: 5229

Just the code inside if (string.length >= 2) :

var elem = $(this);
// save newest search
elem.data('search',search)
// clear pending searches
.clearQueue().stop()
// waits
.delay(250)
// runs search
.queue(function() {
    $.ajax({
        'type': 'GET',
        dataType: 'html',
        'url': url,
        'success': function(data){

        // check if can be run
        if(elem.data('search') != search)
            return;

                // show the search data
        }
    });
});

Upvotes: 1

Thariq Shihipar
Thariq Shihipar

Reputation: 1082

Take a look at the source code for (or consider using) Jquery Autocomplete It does pretty much exactly what you want, it only submits data after a pause to make sure the user is done and it has a cache, amongst other features.

Upvotes: 1

Related Questions