0

I have this following piece of code.

for(i=0;i<ownerOps[0].length;i++){
    // opportunities[i] = "ID #" + ownerOps[0][i].opportunityId + ": Number of Properties - " + ownerOps[0][i].numberOfProperties;
    // console.log(opportunities[i]);
    gets.push($.get("/getOwnerLeadByLeadId?ownerLeadId="+ownerOps[0][i].ownerLeadId,function(ownerLead,status){
        console.log(ownerLead);
        console.log("i="+i);
        ownerOps[0][i].name=ownerLead.name;
        ownerOps[0][i].email=ownerLead.email;
        opportunities[i]="Name :"+ownerOps[0][i].name+' Email :'+ownerOps[0][i].email;
    }))
}

As get is asynchronous the value of i already gets incremented in the success handler . Is there anyway to store the value of i while calling get so that it the proper value of i can be used in the success handler?

Jai
  • 74,255
  • 12
  • 74
  • 103
Sourav Mukherjee
  • 299
  • 7
  • 13

3 Answers3

0

You can use context parameter to store any object and that will be accessible in the success callback. Here you can store the value of var i.

$.ajax({
  url: "test.html",
  context: document.body
}).done(function() {
  $( this ).addClass( "done" );
}) 

http://api.jquery.com/jquery.ajax

Scarecrow
  • 4,057
  • 3
  • 30
  • 56
0

Just wrap your loop body in a function and then simply do something like this:

for(i=0;i<ownerOps[0].length;i++){
    getOwner(ownerOps[0][i], i);
}

then in scope of getOwner you will always have a correct value of i

kriskot
  • 303
  • 1
  • 8
0

Solved it using jquery each.

$.each(ownerOps[0],function(i,ownerOp){
                                // opportunities[i] = "ID #" + ownerOps[0][i].opportunityId + ": Number of Properties - " + ownerOps[0][i].numberOfProperties;
                                // console.log(opportunities[i]);
                                gets.push($.get("/getOwnerLeadByLeadId?ownerLeadId="+ownerOp.ownerLeadId,function(ownerLead,status){
                                    console.log(ownerLead);
                                    console.log("i="+i);
                                    ownerOp.name=ownerLead.name;
                                    ownerOp.email=ownerLead.email;
                                    opportunities[i]="Name :"+ownerOp.name+' Email :'+ownerOp.email;
                                }))
                            })
Sourav Mukherjee
  • 299
  • 7
  • 13