Facebook API – Get friends list

Facebook API – Get friends list

70 318600
Facebook API – Get friends list
Facebook API - Get friends list

Facebook API – Get friends list

In our recent tutorials I told you how to import your contacts from google. Today I decided to make similar tutorial, but for facebook. I think that it can be very interesting for you to get a list of your friends. We are going to use Facebook’s API (javascript api) to build today’s example.

Firstly, we should create our own new application at Facebook. Please follow this link and click ‘Create New App’ button at the left top:

Faceboog Friends API - step 1

We should select our App Name and click ‘Continue’ button. We’ve just got our own api key:

Faceboog Friends API - step 2

Now, please pay your attention to Basic Info block, we should type our App Domains and Site URL params:

Faceboog Friends API - step 3

That’s all, click ‘Save Changes’ button, and lets start coding !


Live Demo

[sociallocker]

download in package

[/sociallocker]


Step 1. PHP

Now, please create an empty index.php file and put next code:

index.php

<?php
$sApplicationId = 'YOUR_APPLICATION_ID';
$sApplicationSecret = 'YOUR_APPLICATION_SECRET';
$iLimit = 99;
?>
<!DOCTYPE html>
<html lang="en" xmlns:fb="https://www.facebook.com/2008/fbml">
    <head>
        <meta charset="utf-8" />
        <title>Facebook API - Get friends list | Script Tutorials</title>
        <link href="css/main.css" rel="stylesheet" type="text/css" />
    </head>
    <body>
        <header>
            <h2>Facebook API - Get friends list</h2>
            <a href="https://www.script-tutorials.com/facebook-api-get-friends-list/" class="stuts">Back to original tutorial on <span>Script Tutorials</span></a>
        </header>
        <img src="facebook.png" class="facebook" alt="facebook" />
        <center>
            <h1>Authorization step:</h1>
            <div id="user-info"></div>
            <button id="fb-auth">Please login here</button>
        </center>
        <div id="result_friends"></div>
        <div id="fb-root"></div>
        <script>
        function sortMethod(a, b) {
            var x = a.name.toLowerCase();
            var y = b.name.toLowerCase();
            return ((x < y) ? -1 : ((x > y) ? 1 : 0));
        }
        window.fbAsyncInit = function() {
            FB.init({ appId: '<?= $sApplicationId ?>',
                status: true,
                cookie: true,
                xfbml: true,
                oauth: true
            });
            function updateButton(response) {
                var button = document.getElementById('fb-auth');
                if (response.authResponse) { // in case if we are logged in
                    var userInfo = document.getElementById('user-info');
                    FB.api('/me', function(response) {
                        userInfo.innerHTML = '<img src="https://graph.facebook.com/' + response.id + '/picture">' + response.name;
                        button.innerHTML = 'Logout';
                    });
                    // get friends
                    FB.api('/me/friends?limit=<?= $iLimit ?>', function(response) {
                        var result_holder = document.getElementById('result_friends');
                        var friend_data = response.data.sort(sortMethod);
                        var results = '';
                        for (var i = 0; i < friend_data.length; i++) {
                            results += '<div><img src="https://graph.facebook.com/' + friend_data[i].id + '/picture">' + friend_data[i].name + '</div>';
                        }
                        // and display them at our holder element
                        result_holder.innerHTML = '<h2>Result list of your friends:</h2>' + results;
                    });
                    button.onclick = function() {
                        FB.logout(function(response) {
                            window.location.reload();
                        });
                    };
                } else { // otherwise - dispay login button
                    button.onclick = function() {
                        FB.login(function(response) {
                            if (response.authResponse) {
                                window.location.reload();
                            }
                        }, {scope:'email'});
                    }
                }
            }
            // run once with current status and whenever the status changes
            FB.getLoginStatus(updateButton);
            FB.Event.subscribe('auth.statusChange', updateButton);
        };
        (function() {
            var e = document.createElement('script'); e.async = true;
            e.src = document.location.protocol + '//connect.facebook.net/en_US/all.js';
            document.getElementById('fb-root').appendChild(e);
        }());
        </script>
</body>
</html>

Now, please pur your application id (and secret) in the beginning of our code, and only after lets review our rest code. In the beginning I prepared a small html code:

<center>
    <h1>Authorization step:</h1>
    <div id="user-info"></div>
    <button id="fb-auth">Please login here</button>
</center>
<div id="result_friends"></div>
<div id="fb-root"></div>

We will display short info about logged in member in ‘user-info’ element. The button (id=fb-auth) will be used as Login/Logout button. And finally, we will display our facebook’s friends in the last one div (id=result_friends).

Now please review our JavaScript code. In the beginning we perform initialization of FB object with our application id. After, we add event handler to our Login/Logout button. We we are not logged in – the script will ask you to login (with your account credentials). If we are logged in, the script will evoke API method /me/friends in order to get a list of our friends. As you can see – we use limits (99 by default) to avoid very long listings. Once we get it (our friends) we display them on the screen.

Step 2. CSS

In order to stylize our output I used next styles:

#result_friends {
    margin: 0 auto;
    overflow: hidden;
    width: 900px;
}
#result_friends h2 {
    text-align: center;
}
#result_friends div {
    border: 1px solid #888;
    box-shadow: 3px 3px 0 #000;
    float: left;
    margin-bottom: 10px;
    margin-right: 10px;
    padding: 5px;
    width: 275px;
}
#result_friends img {
    float: left;
    margin-right: 10px;
}

Live Demo

Conclusion

I hope that everything is clean in today’s code. If you have any suggestions about further ideas for articles – you are welcome to share them with us. Good luck in your work!

SIMILAR ARTICLES


70 COMMENTS

  1. Can you help me to get my Friends’ friends on Facebook?

    For example:
    A is a friend with B
    B is a friend with C , D and E

    A wants a script to get B friends. Please can you help me???

    Thanks again,
    Issa

    • Hi Issa,
      I think that you can refer to https://developers.facebook.com/docs/graph-api/reference/user/friends/ to get friends of a certain member

  2. Hii.. Andrew

    Your tutorial is very helpful. I got the facebook friendslist and the friendsactivity on my website with the help of your tutorial..
    Thanks..

    Also i want to display my photos and videos,events,.. on my website.
    Please help me for that.
    Iam waiting for your script for the above purposes..

    Regards,

    Sijo

  3. HI
    I want to create a phonegap app to fetch the contacts.
    can you guide me about the code that i need to change for that

    regards

    • Hi Nida,
      I haven’t used the phonegap in the past, but as I read from it’s promo text – this is framework to create mobile applications. I think that you should read at least several tutorials about using this framework before you start using it.

  4. Hi Andre i am new to facebook apps,i want your help,my question is i created facebook app and added in facebook developer’s page,in my app i want to get my friends list as suggestion list in text box in a jsp page,can you please help me how to do this,i want your suggestion,thanks in advance

    • Hello Venugopal,
      This tutorial is already about fetching information of your friends – so, you can just use it in order to build your own custom application

Leave a Reply to nida Cancel reply