views:

28

answers:

1

Hello,

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?

+1  A: 

Since those return statements you currently have don't run until later, you need to call any code that relies on the data from the callback, for example:

function check_available() {
  $.post('ajax', {
    action: 'mail'
  }, function(data) {
    myNextFunction($.trim(data) == 'NO_ERROR');
  });
}
function myNextFunction(isAvailable) {
  //do something, this runs after the AJAX request completes the check
}

So instead of treating is synchronosuly with a return statement, 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 undefined because that callback function happens later (after your current code trying to use the value).

Nick Craver