-2

Possible Duplicate:
How to return AJAX response Text?
Variable doesn’t get returned JQuery
AJAX not updating variable

I am having issue with this code:

/**
 * facebook Object*/
var fbObject = new Object();


/**
 * Function to get login status
 * @returns boolean Logged in status
 * */
fbObject.getLoginStatus = function() {
    FB.getLoginStatus(function(response) {
        if (response.status == 'connected') {
              console.log('logged in');
              return true;
            } else {
              console.log('not logged in');
              return false;
            }
    });
}

var status = fbObject.getLoginStatus();

    alert('Status: '+ status);

My problem is that getLoginStatus method isn't returning the value.

Community
  • 1
  • 1
Omer Abbas
  • 39
  • 1
  • 7

3 Answers3

0

You need a callback

Ajax requests do not return anything, they are asynchronous.


Try this:

var status = function(s){
    alert('Status: '+ s);
};

/**
 * Function to get login status
 * @returns boolean Logged in status
 * */
fbObject.getLoginStatus = function() {
    FB.getLoginStatus(function(response) {
        if (response.status == 'connected') {
           console.log('logged in');
           status(true);
         } else {
           console.log('not logged in');
           status(false);
         }
    });
}
Naftali
  • 144,921
  • 39
  • 244
  • 303
0

The method is asynchronous, you are using it in a synchronous manner. It is impossible to return a value in the callback function.

epascarello
  • 204,599
  • 20
  • 195
  • 236
0

The function is Asynchronous,

What I would do is to run the "callback code" in the actual callback:

    fbObject.getLoginStatus = function() {
    FB.getLoginStatus(function(response) {
        if (response.status == 'connected') {
              console.log('logged in');
              alert('Status: '+ true);
            } else {
              console.log('not logged in');
              alert('Status: '+ false);
            }
    });
}

or pass a callback to the function, or stall, until the function has returned.

Hiny
  • 195
  • 7
  • 21