javascript - How to prevent duplicated AJAX call? -



javascript - How to prevent duplicated AJAX call? -

i'm building simple ajax phone call application show result of textbox after typing texts within it:

var delay = (function(){ var timer = 0; homecoming function(callback, ms){ cleartimeout (timer); timer = settimeout(callback, ms); }; })(); $(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(); 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); $("#loadingimg").hide(); } }); },1000); } }); });

fiddle demo

as can see demo above, instance if type test,test1 or test2 or word long length longer 1 it'll create ajax call.

my question is there way allow me prevent duplicate ajax call? illustration if type test in textbox again, it'll show test in div without making ajax phone call fetch result again. give thanks much in advance.

you need cache previous results and, before making ajax call, check cache see if have result in cache.

in javascript, 1 uses object cache:

var delay = (function(){ var timer = 0; homecoming function(callback, ms){ cleartimeout (timer); timer = settimeout(callback, ms); }; })(); // create cache ajax results // key form_data // value whatever ajax phone call returns var 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 cache cached result if (ajaxcache[form_data]) { // uses delay, clears previous timer delay(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); // set result in cache ajaxcache[form_data] = returnhtml; $("#loadingimg").hide(); } }); },1000); } } }); });

working demo: http://jsfiddle.net/jfriend00/p2wrk/

javascript jquery ajax

Comments

Popular posts from this blog

model view controller - MVC Rails Planning -

ruby on rails - Devise Logout Error in RoR -

html - Submenu setup with jquery and effect 'fold' -