var display_welcome = function(){
var fb_login_button = jQuery('#fb_login_button');
var fb_welcome = jQuery('#fb_welcome');
var name = '';
FB.api('/me',function(response){
console.log(response);
name = response.first_name;
});
fb_login_button.css('display', 'none');
fb_welcome.html('<span>Welcome, ' + name + '</span>');
fb_welcome.css('display', 'block');
};
This function is called when a user logs into Facebook from a website. The goal is to display a welcome message to the user with the user's first name. The problem is the variable 'name' is a local variable inside the scope of the callback method of FB.api(). What is the best way to extract this value and use it in my function 'display_welcome'?
The problem is that when you call the
FB.api(...)
function it is asynchronous, that is, your code doesn't stop and wait for the result, it doesn't wait for the callback you supply to be called. Instead the next three lines of code that display your welcome message will be executed before the callback occurs, which means thename
variable will still be blank at the point you try to use it. The solution is as per the other answers, i.e., move your welcome message code into the callback function so that you don't try to usename
until it has been set:(As an aside, and this is my dislike of single-use variables talking: Unless you are using it elsewhere on your page (which presumably you are not since it is local to your
display_welcome()
function) you don't really need thename
variable at all, just useresponse.first_name
directly within the callback.)How about moving those lines of code into the callback of the API? Like so:
var display_welcome = function(){ var fb_login_button = jQuery('#fb_login_button'); var fb_welcome = jQuery('#fb_welcome'); var name = '';
};
I'd do:
Put the rest of your code in the callback function.
I think it would be best to get user info by subscribing to an event after FB.init(). Something like this: