AnchovyLegend AnchovyLegend - 5 days ago 5
Ajax Question

Call AJAX onkeyup event trigger. Use timer and abort to improve performance?

I am relatively new to AJAX and javascript and I am using ajax to generate search suggestions using an onkeyup event. I am trying to use a timer to regulate the number of ajax requests, and the abort function to improve performance. I never used these two functions before and I am unsure if they are set up correctly. I was wondering if someone can take a look and let me know if I am on the right track with these functions? Many thanks in advance.

var ajaxReq = null;
$(".prod-name-input").keyup(function(){
searchword = $(this).val();
//alert(searchword);
if((searchword.length) > 3) {
clearTimeout(timer);
timer = setTimeout(function(){
if (ajaxReq != null) ajaxReq.abort();
var ajaxReq = $.ajax({
url: "invoice-get-data.php?searchword=" + searchword,
dataType: "html",
success: function(data){
$(".smart-suggestions").html(data);
}
});
}, 350);
}
});

Answer

I suggest you to have a look on the excellent article of Ben Alman on throttling / debouncing : http://benalman.com/projects/jquery-throttle-debounce-plugin/ .

What you want to achieve is a debouncing, so with Ben Alman's plugin, you can use :

var ajaxReq = null;  

$(".prod-name-input").keyup($.debounce(350, function(){
    searchword = $(this).val();

    if((searchword.length) > 3) {
        if (ajaxReq != null) ajaxReq.abort();
        ajaxReq =  $.ajax({
            url: "invoice-get-data.php?searchword=" + searchword,
            dataType: "html",
            success: function(data){
                $(".smart-suggestions").html(data);
             }
        });
    }
}));

EDIT :

In fact, it was a debouncing and not a throttling in your case.

I have added a jsfiddle : http://jsfiddle.net/scaillerie/2AFp3/ .

Comments