How can I view my instagram feed without caption

2

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

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);
    }
});
    
asked by anonymous 07.08.2016 / 20:06

1 answer

3

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

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

Something like this:

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);
}
    
07.08.2016 / 21:40