ramz15
ramz15

Reputation: 2401

How to make FB.api call

I am using the FB JavaScript SDK and followed the FB tutorial exactly. I have added the login button, logged in with my FB account and am trying to make a very basic FB.api call but am not getting a proper response even after I login with facebook. Here's the code:

 <script>
   window.fbAsyncInit = function() {
     FB.init({
       appId      : '291660820848913',
       status     : true, 
       cookie     : true,
       xfbml      : true,
       oauth      : true,
     });

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

   };
   (function(d){
      var js, id = 'facebook-jssdk'; if (d.getElementById(id)) {return;}
      js = d.createElement('script'); js.id = id; js.async = true;
      js.src = "//connect.facebook.net/en_US/all.js";
      d.getElementsByTagName('head')[0].appendChild(js);
    }(document));

 </script>

This gives me an alert that says "undefined". Am I doing something wrong?

Upvotes: 1

Views: 7925

Answers (4)

Sajjad Salehi
Sajjad Salehi

Reputation: 105

easily change the line

js.src = "//connect.facebook.net/en_US/all.js";

to this :

js.src = "http://connect.facebook.net/en_US/all.js";

Upvotes: 3

Jonathan Tonge
Jonathan Tonge

Reputation: 1518

You can subscribe to the event:

ie)

FB.Event.subscribe('auth.login', function(response) {
  FB.api('/me', function(response) {
    alert(response.name);
  });
});

Upvotes: 2

Jeremie Dupuis
Jeremie Dupuis

Reputation: 56

Make sure you're logged in before.

FB.login(function(response) {
  console.log(response);
  if (response.status=="connected") {
    console.log("You're loggued in");
    FB.api('/me', function(response) {
       alert(response.name);
      }); 
  } 
});

In this example, I'm forcing the login, but consider checking the status before (http://developers.facebook.com/docs/reference/javascript/FB.getLoginStatus/)

Upvotes: 2

DMCS
DMCS

Reputation: 31860

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

This should only be done if you know the user is authenticated. You should put a call to FB.getLoginStatus() prior to calling the FB.api().

Upvotes: 5

Related Questions