$ .getJSON not working as it should to get image graph API

1

I have this following code where I return comments for a post on facebook.

function pegaFoto(id){
    var url2 = 'https://graph.facebook.com/v2.8/' + from[id] + '/picture?fields=url';
    $.getJSON(url2, function(res2){
    for (var key2 in res2.data) {
        foto[id] = res2.data[key2].url;
        console.log(res2.data[key2].url);
    }
});

}

function refreshCounts() {
    var url = 'https://graph.facebook.com/v2.8/********_*********/comments?fields=from{id}, message&access_token=' + access_token;
    $.getJSON(url, function(res){
        for (var key in res.data) {
            comentario[key] = res.data[key].message;
            from[key] = res.data[key].from.id;
            pegaFoto(key);
            console.log(comentario[key]);     
            console.log(foto[key]);
        }
    });

}

What is strange is that the second function works perfectly and the one above does not work. the variable url2 is being set correctly but $ .getJSON does not execute and I have no idea why

    
asked by anonymous 16.11.2016 / 18:06

1 answer

1

The problem is that by calling the URL of the graph directly after the return is an image, not a JSON. You will have to use the api of facebook to make the call and have the return in JSON format. Something like:

window.fbAsyncInit = function() {
    FB.init({
        appId: 'your-app-id',
        xfbml: true,
        version: 'v2.8'
    });
    FB.AppEvents.logPageView();
};

(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'));

function pegar() {
    FB.api(
        '/4/picture',
        'GET', {},
        function(response) {
            console.log(response); // irá exibir o mesmo retorno da graph explorer
        }
    );

The return will look like this (taken from graph explorer):

{
  "data": {
    "is_silhouette": false,
    "url": "https://fbcdn-profile-a.akamaihd.net/hprofile-ak-xat1/v/t1.0-1/p50x50/12208495_10102454385528521_4749095086285673716_n.jpg?oh=1a5f0703065fe96c49224e520644fff9&oe=58C3A170&__gda__=1489734487_29708b5f264ecdf1dac103a35df9e726"
  }
}

To initialize the api see this documentation: link

If you have more questions, you have the quickstart here .

Edited

You can get the return as JSON by ajax including at the end of the redirect=false URL. The URL would look like:

https://graph.facebook.com/v2.8/4/picture?redirect=false
    
16.11.2016 / 19:03