1

In my JavaScript code below, I cannot get user_likes to take the value of response. I can Console output "response", and it has the values I need. However, when I try to Console output user_likes, I get undefined. What gives?

function fqlUserLikes(user_id) {
    var user_likes;
    FB.api(
        {
            method: 'fql.query',
            query: 'SELECT page_id,name,type FROM page WHERE page_id IN (SELECT page_id FROM page_fan WHERE uid=' + user_id + ')'
        },
        function(response) {
            user_likes=response;
        }
    );
    Console.log(user_likes);
    return user_likes;
}

Thanks for any help, I.N.

3
  • 5
    I'm guessing that the function is asynchronous, so do what you need to do in the callback. Commented Aug 12, 2013 at 20:07
  • 1
    are you able to print out (in an alert or something) the value of response? Commented Aug 12, 2013 at 20:08
  • possible duplicate of How to return the response from an AJAX call? Commented Aug 12, 2013 at 20:23

2 Answers 2

1

Your method is asynchronous, so when you try to log and return the variable, it hasn't actually been assigned yet. Take the below snippet:

//Do what you need to do in here!
function(response) {
    user_likes=response;
});

//The below code is executed before the callback above.
//Also, it should be console, and not Console. JS is case sensi.
Console.log(user_likes);
return user_likes;
Sign up to request clarification or add additional context in comments.

Comments

1

Your function that changes the value of user_likes is not called immediately. FB.api() starts the process of calling the API, and then returns. Your console.log() call happens at this point, and then your function returns the user_likes value to its caller. Then, at some later point, the api call completes, your callback function is called, and it sets user_likes to the appropriate value. Unfortunately, there's nothing left to read that value.

You need to completely restructure your code to make it work. Javascript doesn't really support waiting for things to happen in the middle of code; it's a very asynchronous language. The best way is if you pass a callback function that actually uses the new value, rather than trying to store it in a variable for something else to read.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.