Reputation: 33644
My code is as follows:
jQuery(document).ready(function() {
var pic = 0;
FB.init({appId: '1355701231239404', status: true, cookie: true, xfbml: true});
FB.getLoginStatus(function(response) {
if (response.session) {
pic = "http://graph.facebook.com/" + response.session.uid + "/picture";
alert(pic);
} else {
window.location = "index.php"
}
});
});
</script>
The issue is that the pic inside my if statement has a different scope with the one I declared above? Why and how do I make them the same?
What I want is to use this var pic (the one that has been assigned by the if statement) inside the body of my html. I will have another script inside the body, a document.write that uses this pic variable.. as of now when I do a document.write it always gives me 0, as if it's not assigned inside the if statement
Upvotes: 1
Views: 95
Reputation: 116654
But there is only one pic
in that snippet. So the issue you describe doesn't exist. What problem are you experiencing? How does the code misbehave compared with what you expect?
Update
Okay, your actual problem is that you're expecting pic
to be updated so you can use the value of it elsewhere. But consider:
FB.getLoginStatus(function(response) { ... });
The reason that function executes a callback, instead of returning response
as a return value, is because it is asynchronous. It make take a while to get the response, and so it doesn't execute the callback immediately. So your other piece of code is probably executing before that happens, i.e. before pic
has been properly initialised with a value.
Upvotes: 1
Reputation: 943142
The issue is that the pic inside my if statement has a different scope
No, it isn't. JavaScript scope is by function. var pic = 0;
scopes pic
to the anonymous function passed to ready()
. The anonymous function passed to getLoginStatus()
doesn't use var
at all, so the scope of pic
there is the same.
(Since you didn't say what outcome you got or what outcome you were expecting, it is hard to say what the solution to your problem actually is)
Upvotes: 3