0

This is my function:

function isLoggedIn(){
    $newuid = uid;
    alert("1");

    if(uid == null){return false;}

    $.getJSON("login.jsp",{uname: uname, upass : upass},function(data){
        alert("2");
        $newuid = data.uid;
    });

    alert("3");
    return $newuid == uid;
}

It will alert 1 then 3 and then 2. Why is that and how can i fix it?

user3438815
  • 211
  • 3
  • 12

1 Answers1

2

Because getJSON is asynchronous. When you call getJSON, you start the process, but it completes (and calls your callback) later, when it completes.

For this same reason, it's impossible for your isLoggedIn function to return a value based on the information retrieved via getJSON. Instead, you'll have to have isLoggedIn accept a callback (or return a promise) that it calls (or fulfills) with the result of the getJSON call.

T.J. Crowder
  • 1,031,962
  • 187
  • 1,923
  • 1,875