javascriptjquery

I don't understand how this javascript function executes


When I run the following codes, the alert popup displays undefined. I thought it would return either true or false instead. Please can someone explain how the checkLoginStatus() function excutes. Thanks.

function checkLoginStatus() {
    $.get("func.php", {op:'login_status', r:Math.random()}, function(data) {
        if (data == "Yes") {
            showSalesView();
            return true;
        } else {
            loginView();
            return false;
        }   
    });
}   

alert(checkLoginStatus());

Solution

  • There's a couple things wrong.

    One, you're performing an asynchronous call within the function, so by the time the call has come back, checkLoginStatus has already returned. It essentially looks like this:

    function checkLoginStatus() {
        $.get("func.php", {
            op: 'login_status',
            r: Math.random()
        }, function(data) {
            if (data == "Yes") {
                showSalesView();
                return true;
            } else {
                loginView();
                return false;
            }
        });
        // return undefined
    }
    

    Second, you're returning within the callback of another function, so that return affects the return value of the callback to $.get

    You want to use callbacks. So,

    function checkLoginStatus(callback) {
        $.get("func.php", {
            op: 'login_status',
            r: Math.random()
        }, function(data) {
            if (data == "Yes") {
                showSalesView();
                callback(true);
            } else {
                loginView();
                callback(false);
            }
        });
    }
    

    and then

    checkLoginStatus(function(result) {
        alert(result);
    });