I have some variables that I am setting withing a function. When inside the function I can get, set and alert the uid1 and accessToken2, but if I try to alert them outside of the function, it gives undefined. How can I set the values?
Here is the code:
FB.getLoginStatus(function(response) {
if (response.status === 'connected') {
var uid1 = response.authResponse.userID;
alert(uid1); //works here
var accessToken2 = response.authResponse.accessToken;
alert(accessToken2); //works here
}
else if (response.status === 'not_authorized') { }
else { }
});
alert(uid1); //does NOT work here
alert(accessToken2); //does NOT work here
You declared those variables outside of the scope that you’re using them. To fix your code, declare them outside of the function:
Update: As suggested by the comments below, because your
getLoginStatusmethod is asynchronous, you will likely not have values when you call thealert()outside the method. I have added additional alerts inside the call back to show where you should try to access the values.