3

I have a javascript function which looks like this:

function reloadToolbar() {
        var ids = ["#gs_foo"];
        var parmName = ["foo"];
        for (i = 0; i < ids.length; i++) {
               $.ajax({url:"myurl?parm="+parmName[i],success:function(result){
                 $(ids[i]).html(result);
               }});       
        }
}

However, the above code doesn't work. it doesn't update the id gs_foo. Although, the code below works fine, note the change ($("#gs_foo).html(result))

function reloadToolbar() {
        var ids = ["#gs_foo"];
        var parmName = ["foo"];
        for (i = 0; i < ids.length; i++) {
               $.ajax({url:"myurl?parm="+parmName[i],success:function(result){
                 $("#gs_foo").html(result);
               }});       
        }
}

How can I do this the right way?

birdy
  • 9,286
  • 24
  • 107
  • 171
  • Seems like this question is asked at least once per day. Duplicates: http://stackoverflow.com/questions/3273210/javascript-closures-variable-scope-question, http://stackoverflow.com/questions/1451009/javascript-infamous-loop-problem, http://stackoverflow.com/questions/3572480/please-explain-the-use-of-javascript-closures-in-loops, and many more... It's about closures. Also btw, your `i` variable is global. – elclanrs Dec 04 '12 at 03:05
  • good, thought I was crazy. I looked at the three links posted by @elclanrs and couldn't connect the dots... – birdy Dec 04 '12 at 03:18
  • Now that I double check maybe is not that... Altough it seems like `i` is "lost" inside the success function closure... – elclanrs Dec 04 '12 at 03:40

1 Answers1

0

A work-through is to add another field to your result from server.

$.ajax({url:"myurl?parm="+parmName[i],success:
    function(result){
        var ids= $('.whatever');
        $(ids[result.index]).html(result.body);}
});   
lastr2d2
  • 3,604
  • 2
  • 22
  • 37