node ninja
node ninja

Reputation: 32986

How to use Facebook API to get the name of a friend

Let's say I was able to get the id of a friend. (That unique number that everyone has on Facebook.)

How can I display the name of that friend?

I want to make a javascript alert box like this.

<script type="Javascript/text">
function showname(id)
{
alert("The name of your friend with id " + id + " is " + name)
}
</script>

In the above example, how would I get their name into the name variable?

Upvotes: 0

Views: 2138

Answers (2)

Akshaya Shanbhogue
Akshaya Shanbhogue

Reputation: 1448

You can use the OAuth library for FB or using cURL. If you use cURL, you just have to send a request to https://graph.facebook.com/id and it returns name as a parameter. Refer http://developers.facebook.com/docs/reference/api/

Upvotes: 0

Dmitry Savy
Dmitry Savy

Reputation: 1067

You need to use Graph API like so:

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

        FB.Event.subscribe('auth.login', function(response) {
          window.location.reload();
        });

        FB.api('/me/friends',function(resp) {
            if(resp && resp.data.length) {
                var html = '<ul>';
                for(var i=0; i<resp.data.length; i++) {
                    html += '<li><img src="http://graph.facebook.com/' + resp.data[i].id + '/picture?type=small" />' + resp.data[i].name + '</li>';
                }
                html += '</ul>';
                document.getElementById('friends').innerHTML = html;
            }
        });
      };

      (function() {
        var e = document.createElement('script');
        e.src = document.location.protocol + '//connect.facebook.net/en_US/all.js';
        e.async = true;
        document.getElementById('fb-root').appendChild(e);
      }());
    </script>

Upvotes: 3

Related Questions