The trick in these situations is to nest “successful” callbacks as follows:
$.ajax({
url: "/loadData",
success: function () {
$.ajax({
url: "/saveData",
success: function () {
alert('Data saved');
}
});
}
});
If your function loadData()looks something like this:
function loadData() {
.ajax({
url: "/loadData",
success: function () {
}
});
}
... then you can give it a callback argument that is called immediately before the success callback returns:
function loadData(myCallback) {
.ajax({
url: "/loadData",
success: function () {
if (typeof myCallback === 'function') {
myCallback();
}
}
});
}
Then you can implement your function saveData()as follows:
function saveData() {
loadData(function () {
.ajax({
url: "/saveData",
success: function () {
alert('Data saved');
}
});
});
}
You can still call the function loadData()without any arguments in other parts of your script.
source
share