Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Passing variables to $.ajax().done()

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.

like image 521
Phil Tune Avatar asked Apr 07 '12 23:04

Phil Tune


People also ask

What does AJAX () method do?

The ajax() method is used to perform an AJAX (asynchronous HTTP) request. All jQuery AJAX methods use the ajax() method. This method is mostly used for requests where the other methods cannot be used.

How can I transfer data from one AJAX call to another?

If you want to chain AJAX calls, you need to set the next AJAX call inside the callback of the previous one. This way, the next AJAX call will only be sent after the previous one has completed.


1 Answers

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; } );

like image 195
Darwin Airola Avatar answered Sep 25 '22 15:09

Darwin Airola