-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.

5
  • 1
    Its asynchronous! And you don't return anything from the function, so what would you expect? Commented Dec 19, 2012 at 14:08
  • What is the value you are getting for the response.status?? Commented Dec 19, 2012 at 14:08
  • The reason is simple : when getLoginStatus ends, the distant server hasn't received the question nor answered. So you can't get something returned. Commented Dec 19, 2012 at 14:09
  • @algorhythm Those are probably two distinct functions : one from an API and one from OP. Commented Dec 19, 2012 at 14:10
  • Thank you guys found solution here... stackoverflow.com/questions/12475269/… Commented Dec 19, 2012 at 14:19

3 Answers 3

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);
         }
    });
}
Sign up to request clarification or add additional context in comments.

1 Comment

Tried this but this is also not working :(
0

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

Comments

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.

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.