0

In an $.ajax callback, I want to do something depending on what I receive from the server, which is sending true or false.
The problem is, somewhere in the code, I want a return to fire and it doesn't :

function check()
{
    // $.ajax callback(result)
    {
        console.log(result); //in this case I get 'true' (boolean)
        if(!result)
        {
            // I checked I don't end up here
        }
        else
        {
            console.log('well done'); // shows up in the console
            return "done";
        }
    }
    return "oops";
}

// later in the code
console.log(check()); // displays "oops" whereas the console.log('well done') has showned up in the console

Parts of the function I didn't give you are mostly CSS effects.

Do you have any idea why a return couldn't fire, or what did I miss ? Thanks in advance !

tektiv
  • 14,010
  • 5
  • 61
  • 70
  • 3
    It's not really clear from the code, but the return probably doesn't return because ajax is asynchronous. – adeneo Jul 24 '15 at 09:53
  • @adeneo I just checked, and the `async` parameter is set to `false` – tektiv Jul 24 '15 at 09:54
  • 2
    That's even worse, never use synchronous ajax. – adeneo Jul 24 '15 at 09:58
  • @adeneo Oh I didn't know that. Can you tell me why ? Also, setting the `async` to `true` make the returns fire too late (the console displays `undefined`). how should I do ? – tektiv Jul 24 '15 at 10:01
  • 3
    http://stackoverflow.com/questions/14220321/how-to-return-the-response-from-an-asynchronous-call – adeneo Jul 24 '15 at 10:01
  • @adaneo Well I learnt something today ^^ Thank you for your help – tektiv Jul 24 '15 at 10:07

1 Answers1

1

You are returning a value in a callback, this is why you don't get this value, your code is equivalent to:

function callback (result) {
    if (!result) { }
    else {
        console.log('well done') ;
        return "done";
    }
}

function _ajax (cb) {
    cb (true) ; // Call cb but does not care about the result
    return true ;
}

function check() {
    ajax (callback) ; // Call ajax but does not care about its result
    return "oops";
}

check () ;

If you were doing an asynchronous request, the behaviour would be a bit different, but the idea would remain the same.


You should never do synchronous (a)jax calls, but if you did not care, you could do the following:

function check () {
    var res ;
    $.ajax ({
        success: function (result) {
            if (!result) { res = "fail" ; }
            else {
                console.log('well done') ;
                res = "done" ;
            }
        }
    }) ;
    return (typeof res === 'undefined') ? "oops" : res ;
}
Holt
  • 36,600
  • 7
  • 92
  • 139