How can I view my instagram feed without caption

Asked

Viewed 93 times

2

With this example I am viewing my feeds only with caption, but when I do not put caption appears nothing.

var token = 'XXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX',
userid = XXXXXXXXX,
num_photos = 10;


$.ajax({
    url: 'https://api.instagram.com/v1/users/' + userid + '/media/recent',
    dataType: 'jsonp',
    type: 'GET',
    data: {access_token: token, count: num_photos},
    success: function(data){
        console.log(data);
        for (var x = 0; x < 10; x++) {
            $('ul').append("<li><a href='" + data.data[x].link + "''><img class='top' src=" + data.data[x].images.low_resolution.url + "/><p>" + data.data[x].caption.text + "</p></a></li>");
            //$("ul").append("<li><a target='_blank' href='" + data.data[x].link +"'><img src='" + data.data[x].images.low_resolution.url +"'></img></a></li>");
            //$('ul').append('<p style="color:#0000FF">'+ data.data[x].user.username +'</p>');
        }
        },
    error: function(data){
        console.log(data);
    }
});

1 answer

3


The problem is that in photos that have no caption, data.data[x].caption.text should be evaluating for null, invalidating the whole expression (and then not showing the images).

My suggestion is that you test yourself first data.data[x].caption is true (if the data exists) and then execute the code that reads the images inside it.

Something like that:

for (var x = 0; x < 10; x++) {
    var legenda = data.data[x].caption ? ['<p>', data.data[x].caption.text, '</p>'].join('') : '';
    $('ul').append("<li><a href='" + data.data[x].link + "'><img class='top' src=" + data.data[x].images.low_resolution.url + "/>" + legenda + "</a></li>");
}

or more visually:

for (var x = 0; x < 10; x++) {
    var legenda = data.data[x].caption ? ['<p>', data.data[x].caption.text, '</p>'].join('') : '';
    var html = [
        "<li>",
            "<a href='" + data.data[x].link + "'>",
                "<img class='top' src=" + data.data[x].images.low_resolution.url + "/>",
                legenda,
            "</a>", 
        "</li>"
    ].join('');
    $('ul').append(html);
}

Browser other questions tagged

You are not signed in. Login or sign up in order to post.