jk jk
jk jk

Reputation: 1075

jquery: why i can't return boolean in function

i have current code:

<button onclick="ismeloggedin()">

script:

function ismeloggedin(){
    if(checkloggedin()){
        alert('you"re logged in');
    }else{
        alert('you didn"t login!!!!');
    }
}

function checkloggedin(){
    $.post('/test/check/',{'loggedin':0},function(data,status){
        return (data.status == 'error')?false:true; 
    });
}

php is not necessary but post anyway

function check(){
    is(isset($_POST['loggedin'])){
        if(isLoggedIn()){
            $json = ['status'=>'success'];
        }else{
            $json = ['status'=>'error'];
        }
        header('Content-Type: application/json; charset=utf-8');
        echo json_encode($json);
    }
}

i got the issue is checkloggedin() this function return undefined

instead return true/false

Upvotes: 0

Views: 1793

Answers (2)

Kamil T
Kamil T

Reputation: 2216

function GenerateResult(pResult){
    if(pResult){
        alert('you\'re logged in');
    }else{
        alert('you didn\'t login!!!!');
    }
}

function ismeloggedin(){
    $.post('/test/check/',{'loggedin':0},function(data,status){
        GenerateResult((data.status == 'error')?false:true);
    });
}

Upvotes: 0

Dave
Dave

Reputation: 46249

jQuery's post function is asynchronous. That means that your function is returning before the data is loaded, so there is no way to get that value back to the original function.

You'll have to re-think the structure of your code, remembering that the data will not be immediately available. For example, when the page loads you could send the request, then when it completes (i.e. when your inner function is called) you can modify content on the page accordingly.

Upvotes: 2

Related Questions