Passing variables to $.ajax().done()
Asked Answered
D

2

16

I'm lost. How might I pass a loop variable to an AJAX .done() call?

for (var i in obj) {
   $.ajax(/script/).done(function(data){ console.log(data); });
}

Obviously, if I were to do console.log(i+' '+data) i would return the very last key in the object obj on every single iteration. Documentation fails me.

Debt answered 7/4, 2012 at 23:32 Comment(1)
I figure I could use success, but as I understand that is deprecated now.Debt
C
15

You can use a closure (via a self executing function) to capture the value of i for each invocation of the loop like this:

for (var i in obj) {
    (function(index) {
        // you can use the variable "index" here instead of i
        $.ajax(/script/).done(function(data){ console.log(data); });
    })(i);
}
Clincher answered 7/4, 2012 at 23:39 Comment(2)
Closures are one concept I've always had a tough time understanding fully. Thanks @jfriend00, I'ma try that!Debt
Yep, that worked. I could even do obj[index]. Thanks again!Debt
L
20

You can just create a custom field in the object that you send to $.ajax(), and it will be a field in this when the promise callback is made.

For example:

$.ajax( { url: "https://localhost/whatever.php", method: "POST", data: JSON.stringify( object ), custom: i // creating a custom field named "custom" } ).done( function(data, textStatus, jqXHR) { var index = this.custom; } );

Lucrece answered 1/11, 2016 at 3:28 Comment(3)
After 5 years, I have long since forgotten what even prompted this question. ;)Debt
I needed to know how to do this for a recent project. So, when I figured it out, I tried to also relay the information to others who said that they wanted it...Lucrece
This is better from jquery ajax asynchronous execution point of view, it clearly provide intended item/object reference when callback is executed latter in time.Inshore
C
15

You can use a closure (via a self executing function) to capture the value of i for each invocation of the loop like this:

for (var i in obj) {
    (function(index) {
        // you can use the variable "index" here instead of i
        $.ajax(/script/).done(function(data){ console.log(data); });
    })(i);
}
Clincher answered 7/4, 2012 at 23:39 Comment(2)
Closures are one concept I've always had a tough time understanding fully. Thanks @jfriend00, I'ma try that!Debt
Yep, that worked. I could even do obj[index]. Thanks again!Debt

© 2022 - 2024 — McMap. All rights reserved.