Reputation: 133
I am trying to access first ajax data to add a new value (option2). I can access first ajax data with this.data in beforesend function, but I cannot use "this" in another ajax because it refers to it. So, how to access first ajax data?
$.ajax({
type: "POST",
url: "controller.php",
data: {
'option1': 1
//option2 needs to be accessible here
},
beforeSend: function (jqXHR) {
var firstAjax = this;
$.ajax({
type: "post",
url: "controller.php",
data: {
getNewOption: 1
},
success: function (res) {
firstAjax.data += '&' + $.param({
option2: res
});
}
});
},
success: function (msg) {
//...
}
});
Upvotes: 0
Views: 49
Reputation: 3257
If I understood correctly, you need res
to be part of the data used in the first ajax call, since data
is an object try assigning res to .option2
let me know
$.ajax({
type: "POST",
url: "controller.php",
data: {
'option1': 1
//option2 needs to be accessible here
},
beforeSend: function (jqXHR) {
var firstAjax = this;
$.ajax({
type: "post",
url: "controller.php",
data: {
getNewOption: 1
},
success: function (res) {
firstAjax.data.option2 = res
}
});
},
success: function (msg) {
//...
}
});
EDIT
As nurdyguy accurately pointed out, the second ajax call is indeed running before the first's data is submitted to the server BUT, the second's result, being asynchronous and all, is NOT returning before the first's data is sent, hence the first's data is not leaving with option2
set. Consider this workaround changing the order of the ajax calls:
$.ajax({
type: "post",
url: "controller2.php",
data: {
getNewOption: 1
},
success: function (res) {
$.ajax({
type: "POST",
url: "controller1.php",
data: {
'option1': 1
'option2': res
},
success: function (msg) {
//...
}
});
},
beforeSend: function (jqXHR){}
});
would this be feasible?
Upvotes: 1