javascript - Looping through the ajax call -
i trying loop through ajax calls surprise loop not working.
for (var = 0; < lengthtotal; i++) { $.ajax({ datatype: "json", url: "{{action('reportingcontroller@getdailystats')}}/" + getcampaign[i] + "/" + getstartdates[i] + "/" + getenddates[i] }).done(function(resultthree) { console.debug(i) //is 2 $(resultthree).each(function(index2, value2){ bartable = [ getcampaignname, value2.impressions, value2.clicks ]; xbyxtable($('tbody#stats'), bartable); //valueinside++; }); // end resultthree }); //end done }
this not best practice create functions inside of loop.
try this:
for (var = 0; < lengthtotal; i++) { (function (i) { $.ajax({ datatype: "json", url: "{{action('reportingcontroller@getdailystats')}}/" + getcampaign[i] + "/" + getstartdates[i] + "/" + getenddates[i] }).done(function (resultthree) { console.debug(i) //is 2 $(resultthree).each(function (index2, value2) { bartable = [getcampaignname, value2.impressions, value2.clicks]; xbyxtable($('tbody#stats'), bartable); //valueinside++; }); // end resultthree }); //end done })(i); }
the reason work closures
. variables outside functions accessible inner functions after function exited. here, i
inside for
loop changed until response of ajax comes. using closure
, i
copied local variable of function.
Comments
Post a Comment