Joni Juhani Rautiainen Joni Juhani Rautiainen - 15 days ago 5
jQuery Question

Perform AJAX search one second after multiple keydown events

So I am making a autocomplete with jquery. Ajax is used to get a heavy xml file from remote location. If I search for ex. "Two and a half men" it does about 16 querys (for every letter typed except the 3 first, look the code) with ajax.

I want it to do the Ajax request a second after user has pressed the last key so it will do one query instead of 16.

So if user presses another key before it's been 1 second since the last keydown event, it won't do the query yet.

<script>
$(document).ready(function(){
$('#tv_search').keydown(function(){
var search = $(this).val();
if(search.length >= 3)
{
$.ajax({
type: "GET",
url: "search.php",
data: {show : search, key : '890k4900k0ll' }
}).done(function(msg){
$('#t').html(msg);
});
}
});
});
</script>

Search for series: <input type='text' name='tv_search' id='tv_search'>


Any ideas?

Answer

You could just use a timeout, and clear everytime a key is pressed :

$(document).ready(function() {
    $('#tv_search').on('keyup', function() {
        clearTimeout($(this).data('timer'));
        var search = this.value;
        if (search.length >= 3) {
            $(this).data('timer', setTimeout(function() {
                $.ajax({
                    type: "GET",
                    url: "search.php",
                    data: {
                        show: search,
                        key: '890k4900k0ll'
                    }
                }).done(function(msg) {
                    $('#t').html(msg);
                });
            }, 1000);
        }
    });
});‚Äč