1

THis is my first time trying to use the Facebook javascript SDK so please bear with but I am having issues trying to retrieve an email address from the Facebook API. I have the code below in my site:

<script> window.fbAsyncInit = function() { FB.init({`enter code here` appId : 'my id', xfbml : true, version : 'v2.5' }); }; (function(d, s, id){ var js, fjs = d.getElementsByTagName(s)[0]; if (d.getElementById(id)) {return;} js = d.createElement(s); js.id = id; js.src = "//connect.facebook.net/en_US/sdk.js"; fjs.parentNode.insertBefore(js, fjs); }(document, 'script', 'facebook-jssdk')); </script> 

I think I have connected successfully to the api as when I add a like button for testing:

<div class="fb-like" data-share="true" data-width="450" data-show-faces="true"> </div> 

it seems to load in all buttons from the api.

WHen I try to retrieve a users name however I get an error message saying "undefined". Here is my code for attempting to retrieve username

jQuery(".test123").click(function(){ FB.api( '/me', 'GET', {"fields":"id,name,email"}, function(response) { alert('Your name is ' + response.name); } ); 

I've doublechecked on the Graph API and it seems im using the correct method so not sure what the problem could be and all other articles i've seen seem to make the same call or something similar and more simple like:

FB.api('/me', function(response) { alert('Your name is ' + response.name); }); 

But nothing has worked for me yet.

1 Answer 1

1

You need to authorize the user with FB.login first:

FB.login(function(response) { if (response.authResponse) { //user just authorized your app } }, {scope: 'email,public_profile'}); 

Here´s a tutorial: http://www.devils-heaven.com/facebook-javascript-sdk-login/

...and here´s the official page for FB.login: https://developers.facebook.com/docs/reference/javascript/FB.login/

Without authorization, you can´t get any user data.

Sign up to request clarification or add additional context in comments.

3 Comments

That was it! Thanks :)
quick question. Now that I have the users email address can I retrieve it again when I want to post it to a database? Like is it now saved as a variable? Thanks
you only need to authorize once, see the tutorial for information about how to refresh a user token. of course you can´t just get the info when the user is offline.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.