Reputation: 718
I have a function with Ajax call. If it returns true, another function with another Ajax should be run. But in my case first function returns true but the second function doesn't run. How to do that?
If I remove this: if(checkIfCompleted()) {
from the second function, it's working. But I have to check if first function returns true.
My code is:
function checkIfCompleted() {
$.ajax(
{
url: Base_URL + "/offers/" + 'checkIfQuoteIsComplete',
type: "POST",
data: {
"offer_id": offer_id
},
success: function (data) {
if(data === 'notcompleted') {
$("#NotCompleteQuotes").modal();
return false;
} else {
return true;
}
},
error: function (data) {
MessageBoxError('Error');
}
});
}
Second function that should run after first function returns true is:
function saveOrEditQuote(status, id) {
if(checkIfCompleted()) {
//my code here - it's long
return false;
}
}
Upvotes: 0
Views: 804
Reputation: 4380
All you have to do is pass in the second callback function saveOrEditQuote()
into the body of the success callback. You'll need be careful to declare that function in the right scope, because the success callback will be a different scope than checkIfCompleted
.
Also, often the success argument data
will be an array of objects and strings so data === 'notcompleted'
may be comparing an array to a string.
function checkIfCompleted (){
var success = saveOrEditQuote;
$.ajax({ ... }).success(function(data){ success(true); })
}
function saveOrEditQuote(isCompleted){...};
Upvotes: 0
Reputation: 2390
Javascript is asynchronous, try using callbacks like this
function checkIfCompleted(callback) {
$.ajax(
{
url: Base_URL + "/offers/" + 'checkIfQuoteIsComplete',
type: "POST",
data: {
"offer_id": offer_id
},
success: function (data) {
if(data === 'notcompleted') {
$("#NotCompleteQuotes").modal();
} else {
callback();
}
},
error: function (data) {
MessageBoxError('Error');
}
});
}
then
function saveOrEditQuote(status, id) {
checkIfCompleted(function(){
// will be done only on success
//my code here - it's long
return false;
})
}
Explanation:
A callback is simply another argument, the difference is that it is a function, not for example an integer. By using them you can make sure some block of code is called only after something. They're really helpful for actions that take some time (like requests, jquery animations, timeouts).
Upvotes: 1