Onkeyup ajax call speed trap

This is one good practice in using events on keyup event (when a key is released when user types in a form field). If the event is making an ajax request, this could lower the number of requests made to your web server.

This is the bad, and simple way. One ajax call for each character entered in the text input.

var keyup_handler = function(event){
    jQuery.post("server_script",
                {data: jQuery(this).val();},
                function(data){
                    // some callback, eg:
                    jQuery("#suggestion_box").html(data.suggestion);
                }, 'json');
};
 
jQuery(document).ready(function(){
    // suppose #myinput is the id of a input=text search box
    jQuery("#myinput").keyup(keyup_handler);
});

If the user types “Unbelievable photo”, your js will generate 18 POSTs.
This is the better way. Consecutive key presses under 1 second interval are chained together to make one ajax call. Basically, each event postpones the request if it happens right before the previous one.

var timer = undefined; // must be global referring to keyup_handler context
var ajax_call = function(val){
     jQuery.post("server_script",
                {data: val},
                function(data){
                    // some callback, eg:
                    jQuery("#suggestion_box").html(data.suggestion);
                }, 'json');
      }
var keyup_handler = function(event){
    if (timer != undefined)
        window.clearTimeout(timer);
    timer = window.setTimeout('ajax_call(' + jQuery(this).val(); + ');', 1000);
};
 
jQuery(document).ready(function(){
    // suppose #myinput is the id of a input=text search box
    jQuery("#myinput").keyup(keyup_handler);
});

If the user types “Unbelievable”, waits for a second, and then continues typing ” photo” your js will generate only 2 POSTs. Neat, aie?


  • akeel munshi

    Best one man it worked very well . Please keep sending such helpful tips