Leonajs
Leonajs

Reputation: 361

FB api call in for loop

I'm trying to get all facebook comments with profile pictures of commentators through fb.api() call. Currently all comments gets outputed i just can't get profile pictures to append to appropriate comment.

In for loop which loops through all comments is another FB.api call which gets the profile pic of user who commented on video and than append them into single comment block. With this code i get profile pictures of all users who commented in every single comment. What am i doing wrong?? Thank you in advance!

var komentarji_length = response.comments.data.length;

for (var i = 0; i < komentarji_length; i++) {
    var user_id = response.comments.data[i].from.id;

    FB.api("/" + user_id + "/picture", {
        access_token: access_token
    }, function (response) {
        var profile_pic_link = response.data.url;
        $(".comments_profile_pic" + i).append("<img src=" + comments_profile_pic_link + ">");

    });

    var ime = response.comments.data[i].from.name;
    var message = response.comments.data[i].message;

    $(".fb_comments").append('<div class="single_comment"><div class="comments_profile_pic' + i + '"></div><div class="name">' + name + '&nbsp says:</div><div class="single_message">' + message + '</div></div>');
}

Upvotes: 2

Views: 605

Answers (1)

Sahil Mittal
Sahil Mittal

Reputation: 20753

Issue 1: comments_profile_pic_link is not defined, the variable is: profile_pic_link.

But then also the problem will not be solved. When you call "/" + user_id + "/picture" it is redirected to the image url automatically. So you can directly use the image url as: https://graph.facebook.com/{user-id}/picture. No need to make the API call unnecessarily.

Example


Still if you wish to get the proper image url (not required though), use redirect=0 with your call-

 FB.api("/" + user_id + "/picture?redirect=0", {
     access_token: access_token
    }, function (response) {
    var profile_pic_link = response.data.url;
    $(".comments_profile_pic" + i).append("<img src=" + comments_profile_pic_link + ">");
});

Upvotes: 2

Related Questions