How To Get The Value Of Str Variable?
Solution 1:
How about this:
function Login() {
FB.login((response) => {
if (response.authResponse) {
getPhoto((str) => {
console.log(str);
});
} else {
console.log('User cancelled login or did not fully authorize.');
}
},{scope: 'email,user_photos,user_videos,publish_actions'});
}
function getPhoto(callback) {
FB.api('/me/picture?type=normal', (response) => {
const str = '<br/><b>Pic</b> : <img src="' + response.data.url + '"/>';
document.getElementById('status').innerHTML += str;
callback(str);
});
}
There are other solutions too (for example, with Promises), but using a callback function is very easy. I also added ES6 syntax (const, arrow functions).
You can also use FB.getLoginStatus
to check if the user is logged in on page load, and call getPhoto
in the callback of that function too.
For example: http://www.devils-heaven.com/facebook-javascript-sdk-login/
Solution 2:
In the CONSOLE2 block, you explicitly define the variable str:
var str=...
But in CONSOLE1 block, you never actually define the variable. When the function getPhoto terminates, the variable str goes out of scope and no longer exists.
To fix it, put your logic inside the callback function on the FB.api call. You can place that call inside the FB.login callback function rather than in its own function. Like this:
FB.login(function(response) {
if (response.authResponse) {
FB.api('/me/picture?type=normal', function(response) {
...
In javascript, you have to chain or nest your callbacks. You have to wait for the login callback, then make the next API call, then make your get picture callback, etc.
Solution 3:
The scope of str var remains inside the getPhoto function. For getting value in CONSOLE1 you need to do return value of str from getPhoto function.
Hope this helps you.
Post a Comment for "How To Get The Value Of Str Variable?"