javascript - using $.post() within a loop -


i may doing silly here. user can have multiple "sites" , each site have run calculations come total. have php page these calculations can call calculate.php. returns string ex: 50 parse float in js. here's i'm trying do: total of of numbers outputted calculate.php.

my idea loop through sites, $.post() calculate.php within every iteration (other things being done in loop, less important) , add variable in callback function. believe problem $.post() async... here sample code:

function systems(sitelist){      var runningtotal = 0;      (var ii=0,i<sitelist.length,i++){           $.post("calculate.php",{foo:sitelist[ii]},function(data){          // important part         runningtotal = runningtotal + data          })      }      //outside loop     alert(runningtotal)  } 

this function may imperfect, real question how can achieve result i'm looking here? know, runningtotal alerts 0 above code.

thanks

edit: help. can see, not wise of me using many ajax calls instead of directly fixing problem, believe take step , take advice of sending 1 ajax callback perform task of summing me. again

i'd suggest make use of $.when , run callback once ajax calls done. @ moment have access response of each ajax call , can perform necessary computation.

for example:

function systems(sitelist){      var promises = [];      (var ii=0; i<sitelist.length; i++){         // `$.post` returns promise. keep track of each promise.         promises.push($.post("calculate.php",{foo:sitelist[ii]}));     }      $.when.apply($, promises).then(function() {         // called once responses of ajax calls          // have been received         var sum = 0;         (var = 0, l = arguments.length; < l; i++) {             sum += +arguments[i][0]; // value must cast number first         }         alert(sum)     }); } 

have @ jquery documentation learn more promises: http://learn.jquery.com/code-organization/deferreds/.


in general though, it's better make few ajax requests possible. if can change server side code, change accept list of values, not 1 value, , let server return final result.


Comments

Popular posts from this blog

c++ - Creating new partition disk winapi -

Android Prevent Bluetooth Pairing Dialog -

VBA function to include CDATA -