I'm trying to pass a variable inside a Jquery POST
method from an object array that I get from an asynchronous IndexedDB call using YDN-DB.
Basically db.values
, returns an object array of records stored with information I want to send to a PHP script. I can access the ID
or any other field of the record set like r[i].id
. The only problem is that I can't access it from the inside of the POST's DONE
method so I can delete the record by its ID
after it was successfully processed by the PHP script.
Below is what I want to achieve, everything works fine, the only problem is when I try to delete the processed record:
var req = db.values('table');
req.done(function(r){
for(i=0;i<r.length;r++){
var post = $.post('myscript.php', {'sale[]': $.toJSON(r[i])});
post.done(function(data){
if(data == 'ok'){
db.remove('table',r[i].id);
}
});
}
});
Is there a way to do this, and get the ID
of the processed record to be deleted instead using its array's position?
Thanks!
The problem is that the closure for the callback function captures the same i
variable for all iterations, so when the callsbacks are called the value of i
has passed the last item of the array. You can wrap the code in the loop inside a function to create a separate i
variable for each iteration:
var req = db.values('table');
req.done(function(r){
for(i=0;i<r.length;r++){
(function(i){
var post = $.post('myscript.php', {'sale[]': $.toJSON(r[i])});
post.done(function(data){
if(data == 'ok'){
db.remove('table',r[i].id);
}
});
})(i);
}
});