Skip to content Skip to sidebar Skip to footer

How To Prevent Duplicated Ajax Call?

I'm currently building a simple AJAX call application which will show the result of a textbox after typing some texts inside it: var delay = (function(){ var timer = 0; return

Solution 1:

You just need to cache previous results and, before making the ajax call, check the cache to see if you already have that result in the cache.

In Javascript, one usually uses an object for a cache:

var delay = (function(){
  var timer = 0;
  returnfunction(callback, ms){
    clearTimeout (timer);
    timer = setTimeout(callback, ms);
  };
})();

// create cache for ajax results// the key is the form_data// the value is whatever the ajax call returnsvar ajaxCache = {};

$(document).ready(function(e) {

    $("input[name=html]").keyup(function(e) {
        if(this.value.length > 1) {        
            e.preventDefault();
            var form = $(this).closest('form');
            var form_data = form.serialize();
            // check the cache for a previously cached resultif (ajaxCache[form_data]) {
                 // this uses delay, only so that it clears any previous timerdelay(function() {
                     $("#result").html(ajaxCache[form_data]); 
                     $("#loadingimg").hide();
                 }, 1);
            } else {
                var form_url = form.attr("action");
                var form_method = form.attr("method").toUpperCase();
                delay(function(){
                    $("#loadingimg").show();
                    $.ajax({
                        url: form_url, 
                        type: form_method,      
                        data: form_data,     
                        cache: false,
                        success: function(returnhtml){                          
                            $("#result").html(returnhtml); 
                            // put this result in the cache
                            ajaxCache[form_data] = returnhtml;
                            $("#loadingimg").hide();                    
                        }           
                    });    
                },1000);
            }
        }
    });
});

Working demo: http://jsfiddle.net/jfriend00/P2WRk/

Post a Comment for "How To Prevent Duplicated Ajax Call?"