0

I have this code:

$.post("call.php", {form: data.item.value, positiony: t}, function (data){ top[t] = data;});
$("#pos" + t).css("margin-top", top[t] );

where I call a page with function post of ajax and the returned value is used to set margin-top of a series of div with increment id #pos0, #pos1...; if I change t with number, n times, where n is the number of divs, I have no problem; but if I use 'for' to increment the value, I have undefined variable t in the lambda function; in fact if I print top[t] after lambda function, the value printed is undefined. How can I resolve?

dav04
  • 19
  • 7

1 Answers1

1

Ajax is asynchronous. Your second line is running before the ajax call completes. Move it into the success handler:

$.post("call.php", {form: data.item.value, positiony: t}, function (data){
    top[t] = data;
    $("#pos" + t).css("margin-top", top[t] );
});

Also, if you're doing this in a loop using t as a counter, note that all your success functions will have an enduring reference to the t variable, not a copy of it as of when they were created. So you may want a builder function, or just Function#bind:

for (t = something; t < somethingElse; ++t) {
    $.post("call.php", {form: data.item.value, positiony: t}, function (tValue, data){
        top[tValue] = data;
        $("#pos" + tValue).css("margin-top", top[tValue] );
    }.bind(null, t));
}
T.J. Crowder
  • 1,031,962
  • 187
  • 1,923
  • 1,875