views:

821

answers:

1

Hi everyone, I have an array with objects, I want to save each one of them via GET, and update certain params in the callback, bot

the html:

<html><body><div id='test'><div id="a">a</div><div id="b">b</div></div></body></html>

the js:

$.map($("#test > div"), save)

save = function(o,i){
 itt = $(o)
 tmp = {'desc':itt.html()};
 $.get('ajax/update_post', {'data':array2json(tmp)}, function(a){ 
   alert(itt.attr('id'))
   updatePostBack(a,itt)
   })
 }

updatePostBack = function(a,item){
 alert(item.attr('id'))
}

the updatePostBack is always receiving the las item! how can I pass the right id or object to a callback function in js / jquery?

+1  A: 

The solution is so sadly mundane: you needed to add var in front of your variables to declare them as new. They were being overwritten inappropriately by the next iteration before the first one could complete. This code works for me:

save = function(o,i){
    var itt = $(o)
    var tmp = {'desc':itt.html()};
    $.get('ajax/update_post', {'data':array2json(tmp)}, function(a){
        alert(itt.attr('id'))
        updatePostBack(a,itt)
    })
}

updatePostBack = function(a,item){
    alert(item.attr('id'))
}

$.map($("#test > div"), save);

I also moved the map statement to the end so that it's calling the save function after it's been declared.

Gabriel Hurley
ok, I tested this solution and it certainly is. thank you a lot, Javascript Lord u.u
dnuske
np, glad I could help.
Gabriel Hurley