I have a JavaScript function inside which I use jQuery .post,
and I wanted to return a boolean in the fallback:
function is_available() {
$.post('ajax', {
action: 'mail'
}, function(data) {
if ($.trim(data) == 'NO_ERROR') {
return true;
} else {
return false;
}
});
}
but the function returns undefinied.
How could I return that boolean?
Since those
returnstatements you currently have don’t run until later, you need to call any code that relies on the data from the callback, for example:So instead of treating is synchronosuly with a
returnstatement, treat the code path as asynchronous, and kickoff whatever code needs that “is available” value from the callback of$.post(), it’ll execute when the server request comes back and that boolean you need is ready to use.Currently it’s returning
undefinedbecause that callback function happens later (after your current code trying to use the value).