Robert Dewitt
Robert Dewitt

Reputation: 324

How to use Graph API to get user's total friend count [JavaScript]

After doing some research into Facebook's Graph API v2.8, I finally understand how to craft functions using JavaScript. What I would like to specifically do is after I have the user logged into my application, they would click a button that grabs a total of their friend count.

Here is the code I'm attempting to use to accomplish this:

HTML

<button onclick="getInfo()">Get Friend Count</button>

JavaScript

// Get Basic User Info
// TODO: Get user's friend count
function getInfo() {
FB.api('/me/friends', 'GET', {
    fields: 'total_count'
}, function (response) {
    document.getElementById('status').innerHTML = response.id;
});
}

Perhaps the fields parameter is wrong? The ultimate goal is that I want the total count of friends publicly displayed on a user's profile within my application.

EDIT: user_friends has been authorized with the access token that I generated, but my response.id comes back as undefined.

EDIT 2: The data returned using the Graph API Explorer comes in a JSON format:

{
"id": "my_id",
"name": "my_name",
"friends": {
"data": [
],
"summary": {
  "total_count": 161
  }
 }
}

Upvotes: 3

Views: 3982

Answers (2)

Robert Dewitt
Robert Dewitt

Reputation: 324

Please note that I wrote this in 2017, and the API may have changed since then, especially after the whole Cambridge Analytica thing.

Good news! I solved it by digging deeper into some source code that I found at this site: http://snowadays.jp/test/fb_friend_test.html

Here is the JavaScript:

function getInfo() {
FB.api('/me/friends', 'GET', {fields: 'summary'}, function(response)
{
document.getElementById('status').innerHTML = 
response.summary.total_count;
});
}

Upvotes: 3

Nico
Nico

Reputation: 7256

Your apps needs user_friends authorization, and note that only friends who installed the app are returned in API v2.0 and higher.
Before using Javascript SDK i suggest to do some testings with the Graph explorer

Upvotes: 0

Related Questions