asp.net mvc - How to retrieve a variable in jquery ajax .done() -


stackoverflow(ers),

i have created javascript function in process data array of objects, , in function iterating through array calling ajax request each object in array.

however, inside ajax.done() function, need pass in index of iteration, j. inside iteration, however, j stuck on 4, whereas outside iteration, j counts iteration. note iteration in code below loops through inside each ajax request pull out values form array, can ignored.

can me in working out need make j iterate inside .done() block?

thanks, jamie

object passed code:

var dataconfig = [             { targetdiv: "#chart", charttitle: "title", tooltipvisible: true, xaxislabel: "label", leftyaxislabel: "unit"  },             { apiurl: "url", type: "column", yaxis: "right", visibleinlegend: false },             { apiurl: "url", type: "line", yaxis: "left", visibleinlegend: false },             { apiurl: "url", type: "line", yaxis: "left", visibleinlegend: false },          ]; 

the code:

for ( var j = 2; j < dataconfig.length; j++ ) {                 console.log(j);                 chartconfig[j] = {                      yaxisvalues: [],                      type: dataconfig[j].type,                      yaxis: dataconfig[j].yaxis,                      visibleinlegend: dataconfig[j].visibleinlegend                 }                 $.ajax({                     url: baseurl + dataconfig[j].apiurl,                     beforesend: function ( xhr ) {                         xhr.setrequestheader('authorization', 'yes');                     }                 }).done(function (data) {                    //get y axis values                     var yaxisdata = data.dataseries.data;                     yaxisvalues = [];                     ( var = 0; < yaxisdata.length; i++ ) {                         var yaxisvalue = yaxisdata[i].y[0];                         yaxisvalues.push(parseint(yaxisvalue, 10));                     };                     console.log(yaxisvalues);                     console.log("j:", j);                     // chartconfig[j].yaxisvalues = yaxisvalues;                 });              }; 

ajax asynchronous. .done() method run @ point out of sync parent loop, can't rely on variable 'j'.

you can use following syntax achieve want capturing value of j in self executing function:

for ( var j = 2; j < dataconfig.length; j++ ) {     (function(index) {         $.ajax({             url: baseurl + dataconfig[j].apiurl,             beforesend: ...         }).done(function(data) {             console.log(index);          });     })(j); } 

Comments

Popular posts from this blog

javascript - DIV "hiding" when changing dropdown value -

Does Firefox offer AppleScript support to get URL of windows? -

android - How to install packaged app on Firefox for mobile? -