Fetch a single random profile image from a Facebook user's list of friends using Javascript

I'm currently facing an issue with displaying a random profile picture of the user's friends on Facebook. I attempted to troubleshoot it myself but ended up crashing the login button and now it's not functioning properly. Can someone please help me identify what went wrong in the code I added to my JavaScript file?

This is the code snippet I experimented with:

    /* implementing the API call */
function gatherInfo() {
    FB.api('/friend-list-id/members', 'GET', {
      fields: 'first_name,last_name,name,id,picture.width(100).height(100)'
  }, function (response) {
    console.log(response);// Inspect the response in the console
    document.getElementById('status').innerHTML = "<img src='" + response.picture.data.url + "'><br>" + response.name;

    }); 

Javascript Section:

window.fbAsyncInit = function() {
  FB.init({
    appId: '',
    xfbml: true,
    version: 'v2.5'
  });

  FB.getLoginStatus(function(response) {
    if (response.status === 'connected') {
      document.getElementById('status').innerHTML = 'Connection successful.';
      document.getElementById('login').style.visibility = 'hidden';
    } else if (response.status === 'not_authorized') {
      document.getElementById('status').innerHTML = 'Not logged in.'
    } else {
      document.getElementById('status').innerHTML = 'You are not logged into Facebook.';
    }
  });
};
(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'));

// Sign in using Facebook with additional permissions
function logIn() {
  FB.login(function(response) {
    if (response.status === 'connected') {
      document.getElementById('status').innerHTML = "<img src='http://www.webdevelopmenthelp.net/wp-content/uploads/2015/04/loading.gif' />";
      document.getElementById('login').style.visibility = 'hidden';
      gatherInfo();// Call the function here
      name();
    } else if (response.status === 'not_authorized') {
      document.getElementById('status').innerHTML = 'Not logged in.'
    } else {
      document.getElementById('status').innerHTML = 'You are not logged into Facebook.';
    }
  }, {
    scope: 'email'
  });
}

// Retrieve basic user information
function gatherInfo() {
  FB.api('/me', 'GET', {
    fields: 'first_name,last_name,name,id,picture.width(100).height(100)'
  }, function(response) {
    console.log(response);// Check the response in the console
    document.getElementById('status').innerHTML = "<img src='" + response.picture.data.url + "'><br>" + response.name;

  });


    /* Implementing the API call */
function gatherInfo() {
    FB.api('/friend-list-id/members', 'GET', {
      fields: 'first_name,last_name,name,id,picture.width(100).height(100)'
  }, function (response) {
    console.log(response);// Inspect the response in the console
    document.getElementById('status').innerHTML = "<img src='" + response.picture.data.url + "'><br>" + response.name;

    });     
}   

Thank you in advance for any help provided.

Answer №1

Include the scope user_friends when calling the login function.

{scope: 'email,user_friends'}

Create a function called friends:

function getFriendRandom(cb) {
  FB.api('/me/friends',{
      fields: 'name,id,picture.width(100).height(100)'
    }, function (response) {
    if (response && !response.error) {
     var random = Math.floor(Math.random()*response.data.length);
     cb(response.data[random].picture.data.url);
    }
  });
}
//usage
getFriendRandom(function(image){
  console.log(image);
});

The API v2.0 and higher only return friends who have installed this app. The total_count in summary represents the total number of friends, including those who haven't installed the app.

Refer to the documentation at https://developers.facebook.com/docs/graph-api/reference/v2.5/user/friends

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

Unable to transfer an array from getStaticProps method in Next.js

Whenever I pass a JSON array from getStaticProps in Next.js, I encounter this specific error message when trying to access it. TypeError: Cannot read property 'contentBody' of undefined module.exports../pages/[author]/[article].js.__webpack_expo ...

Selenium - How to pass a file path to a dynamically generated input element that is not visible in the DOM

Check out this example of HTML code: This is how you create a visible button and display the selected file: <button id="visible-btn">visible button</button> <p>selected file is: <span id="selected-file"></spa ...

Tips for testing components with React JS using jest and enzyme

Attempting to perform a unit test on the code snippet below: handleChange = (e) => { let localState = Object.assign({}, this.state) localState[e.target.name] = e.target.value this.setState(localState) this.props.addMetaInformation(localState) } } I&a ...

RaphaelJS: Ensuring Consistent Size of SVG Path Shapes

I am currently constructing a website that features an SVG map of the United States using the user-friendly usmap jQuery plugin powered by Raphael. An event is triggered when an individual state on the map is clicked. However, when rendering a single stat ...

Retrieve all instances of a key-value pair within an object that share the same key

Here is some JSON data: [{"name":"David","text":"Hi"},{"name":"Test_user","text":"test"},{"name":"David","text":"another text"}] I am l ...

Split the text using the newline character (' ') and not the double newline character (' ')

Looking to create a filter that separates all \n and combines them back as \n\n. Is it possible to only target the single \n without affecting the double \n\n? Currently, the issue arises when the input field loses focus, caus ...

Issue Encountered While Attempting to Show a Div Element within a Function

Check out this HTML code snippet: <div class="div1" id ="div1" onclick="onStepClicked()" style ="text-align:center">Step 1</div> And here is the corresponding Script: function onStepClicked() { var elem = document.getElementById(&apo ...

Having difficulties achieving successful API requests in Next.js and Snipcart

I'm currently diving into the world of Snipcart, and I'm encountering some issues connecting to your API. I'm using Next.js and haven't been able to find any solutions on the forum or in the documentation that address my specific proble ...

Problem with vueJS List Transition not being triggered

Within my Vue JS App, I encountered a situation where I have a list of items that change order randomly when the user clicks a button. Despite successfully using Vue.set to dynamically reposition the list elements, I faced an issue with adding a transition ...

Bringing back a Mongoose Aggregate Method to be Utilized in Angular

I'm having trouble returning an aggregate function to Angular and encountering errors along the way. I would really appreciate some assistance with identifying the mistake I am making. The specific error message I receive is Cannot read property &apos ...

Changing from system mode to dark mode or light mode

Within my Next.js web application, I am implementing MUI to facilitate the transition between system, light, and dark modes. Persistence between sessions is achieved by storing the selected theme in local storage. The user has the option to change the them ...

Invoking JavaScript function from an Android Activity

I have a simple JS function that is supposed to set values of some html contents, but it doesn't seem to be working properly. Here is the code for the JS function: function SetEdits(name,email,pic,date) { document.getElementById("myPic").src=pic; doc ...

retrieve the status of a checkbox in a dynamically generated element

I'm currently working on integrating the YouTube API into my app in order to display a dynamic list of cards. The cards are stored in a variable and then added to a playlist container using an each function. Each card contains a toggle switch for use ...

How come the array's length is not appearing on the browser screen?

Code: initialize: function() { this.todos = [ {id: 100, text: 'Rich'}, {id: 200, text: 'Dave'} ]; }, activeTodos: function() { this.todos = this.todos.length(function() { return this.todos; }); ...

The Link component in the router dom should only be active when validation passes successfully

I am looking for a way to prevent the Link component in react-router-dom from functioning until all validations are successfully completed. Removing the link allows the validation to work as intended. I have come across something related to ifValidate, bu ...

Unable to retrieve the value from a textarea when using Shopify Product Options by Bold

I'm currently facing an issue trying to retrieve the value of a textarea using Shopify's Product Options by Bold. The code works fine locally, but when I transfer it over to Shopify, I am unable to get the value. Despite looking at various resour ...

Having trouble changing fonts in JavaScript Photoshop using scripting on certain fonts

I have created a script for photoshop that is designed to change the font family to a different type. However, I am experiencing some inconsistencies in its performance. Here is the section of the script responsible for altering the font family: var origD ...

JavaScript parameter not found

I am currently working on a block type plugin for Moodle and encountering some difficulties with my JS code. Due to my limited knowledge in JS and JSON, I am having trouble identifying the issue at hand. My code includes a function that adds a custom actio ...

Can you explain the process of variable allocation?

I have a query regarding the following JavaScript code snippet. It might be a basic question, but I'm seeking clarification. // 'response' contains JSON data received from the backend: ....then(response => { this.myVar = response.data; ...

FitText.js malfunctioning

I'm currently experimenting with using FitText.js to dynamically adjust the size of headlines to fit within the limits of the browser width. Interestingly, while this script successfully resizes the text in multiple sections of my website, it seems t ...