Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Promote callback onSuccess return value to the Caller Function return value

I have a javascript function that calls a generic function to make an ajax call to the server. I need to retrieve a result (true/false) from the callback function of the ajax call, but the result I get is always 'undefined'.

A super-simplified version of the generic function without all my logic would be:

function CallServer(urlController) {
    $.ajax({
        type: "POST",
        url: urlController,
        async: false,
        data: $("form").serialize(),
        success:
            function(result) {
                if (someLogic)
                   return true;
                else
                   return false;
            },
        error:
            function(errorThrown) {
                return false;
            }
    });
}

And the function calling it would be something like:

function Next() {
        var result = CallServer("/Signum/TrySave");
        if (result == true) {
            document.forms[0].submit();
        }
    }

The "result" variable is always 'undefined', and debugging it I can see that the "return true" line of the callback function is being executed.

Any ideas of why this is happening? How could I bubble the return value from the callback function to the CallServer function?

Thanks

like image 348
antonioh Avatar asked Apr 20 '09 14:04

antonioh


1 Answers

Just in case you want to go the asynchronous way (which is a better solution because it will not freeze your browser while doing the request), here is the code:

function CallServer(urlController, callback) {
    $.ajax({
        type: "POST",
        url: urlController,
        async: true,
        data: $("form").serialize(),
        success:
            function(result) {
                var ret = ( someLogic );
                callback(ret);
            },
        error:
            function(errorThrown) {
                return false;
            }
    });
}

function Next() {
    CallServer("/Signum/TrySave", function(result) {
        if (result == true) {
            document.forms[0].submit();
        }
    });
}
like image 165
Vincent Robert Avatar answered Oct 15 '22 15:10

Vincent Robert