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?

3
  • Seems like this question is asked at least once per day. Duplicates: stackoverflow.com/questions/3273210/…, stackoverflow.com/questions/1451009/…, stackoverflow.com/questions/3572480/…, and many more... It's about closures. Also btw, your i variable is global. Commented Dec 4, 2012 at 3:05
  • good, thought I was crazy. I looked at the three links posted by @elclanrs and couldn't connect the dots... Commented Dec 4, 2012 at 3:18
  • Now that I double check maybe is not that... Altough it seems like i is "lost" inside the success function closure... Commented Dec 4, 2012 at 3:40

1 Answer 1

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);}
});   
Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.