I've got myself a bit confused here.
I've written a bunch of Ajax functions that trigger each other in succession following a valid success
response from the previous one.
Example... (I've removed massive parts of the code that check for various data.response
's to make it clearer).
var var1 = "";
var var2 = "";
var var3 = "";
$(document).ready(function(){
functionOne();
});
function functionOne() {
$.ajax({
url: "http://somewebsite.com/api/index.php",
dataType: "json",
method: "POST",
cache: false,
data : {
"action": "new",
"id": 1234,
"amount": 10
},
success: function(data) {
if(data.response == "Y") {
var1 = data.var1;
var2 = data.var2;
var3 = data.var3
functionTwo(var1, var2, var3);
}
},
error : function(xhr, status) {
console.log("something went wrong");
},
timeout: 200000
});
}
functionTwo(var1, var2, var3) {
$.ajax({
url: "http://somewebsite.com/api/index.php",
dataType: "json",
method: "POST",
cache: false,
data : {
"action": "check",
"id": var1,
"amount": var2,
"var3" : var3
},
success: function(data) {
if(data.response == "Y") {
var1 = data.var1;
var2 = data.var2;
var3 = data.var3
functionThree(var1, var2, var3);
}
},
error : function(xhr, status) {
console.log("something went wrong");
},
timeout: 200000,
});
}
And so on...
But I'm now planning to move them all into one single function which will spit out the result of all functions at the end.
I was going to nest the Ajax requests using success:
but then started reading about .done()
and how this is a much better approach, especially for chaining functions like this.
But I'm a bit confused on how I would send the differing POST data and variables to subsequent calls using this method.
I've seen this here but it doesn't go into any detail of how to pass in the new POST
data elements for the new request.
asyncCall()
.then(function(data1){
// do something...
return anotherAsyncCall();
})
.then(function(data2){
// do something...
return oneMoreAsyncCall();
})
.then(function(data3){
// the third and final async response
})
.fail(function(err) {
// handle any error resulting from any of the above calls
})
.done();
Could somebody please show me a rough example of how to fire functionOne
using .done()
to call functionTwo
passing in the three variables created in functionOne
and the new
data: action
for the second Ajax request).