red house 87
red house 87

Reputation: 2415

Facebook api undefined issue

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.

Upvotes: 1

Views: 3056

Answers (1)

andyrandy
andyrandy

Reputation: 73984

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.

Upvotes: 1

Related Questions