Duc Phan
Duc Phan

Reputation: 185

Access facebook json response object

I have an json response from facebook like this picture. This is my return json from facebook

This is the way i tried to access the likes count data.posts.data[0].likes.count but it kept showing undefined error and i also tried to access comments object like this data.posts.data[0].comments.length it showed the same error. I am stuck here anyone could help me out?

This is my used code to get json

var fburl = "https://graph.facebook.com/128618520547487/?fields=posts.fields(picture,comments,likes,source,link,message)&access_token=CAACEdEose0cBAFOZAdI3zIOmKwkCi2tUZCAl2tpuIyh3WuE5B4njTviyzk4msgZCnKBVTNuXh2FQTf4XkfatgVHYer43TTw2kqV2vxHsjNbjbjiUPKToBrCpUP6ZBhVbr00GQTqjcCynzdGHHObe8OwYK7UMXLcZD";
      var data;
      $('.home-blog').append('<img class="lo" src="<?= BASE_PATH ?>img/loader6.gif"/>'); 
      $.getJSON(fburl, function(json){

          }).done(function( data ) {
              $('.lo').remove();

              for(var i = 0;i<10; i++){
                  if(data.posts.data[i].picture != undefined){
                    console.log(data.posts.data[i].likes.count);

                  }
              }
          })
          .fail(function( jqxhr, textStatus, error ) {
              $('.lo').remove(); 
              $('.home-blog').append('<div class="home-blog-slot"><h2>Error while loading!!! please Click refresh or F5</h2></div>');
          });

Upvotes: 0

Views: 424

Answers (1)

Dave Chen
Dave Chen

Reputation: 10975

It works fine when I do it like this:

<script src="//ajax.googleapis.com/ajax/libs/jquery/1.9.1/jquery.min.js"></script>
<script>
    $(document).ready(function () {
        $.ajax("https://graph.facebook.com/128618520547487/?fields=posts.fields(picture,comments,likes,source,link,message)&access_token=CAACEdEose0cBAFOZAdI3zIOmKwkCi2tUZCAl2tpuIyh3WuE5B4njTviyzk4msgZCnKBVTNuXh2FQTf4XkfatgVHYer43TTw2kqV2vxHsjNbjbjiUPKToBrCpUP6ZBhVbr00GQTqjcCynzdGHHObe8OwYK7UMXLcZD", {
                dataType: "jsonp",
                jsonp: 'callback',
                success: function (json) {
                    console.log(json.posts.data[0].likes.count);
                }
            });
    });
</script>

You MUST use jsonp when accessing files that are not on your own server. Please read sop.

Upvotes: 1

Related Questions