Reputation: 27087
I am trying to get a feed from Instagram using JSON and jQuery to pull specific hashtag images from one particular user - it has been crazy so far and all built from scratch.. now I am stuck - my loop keeps saying Undefined x
This is my code
// GET INSTAGRAM FEED
// Get feed from Instagram based on Hashtag and filter by user
//
var username = 'jdsportsofficial';
var hashtag = 'crlifestyle';
var clientId = '5a79ddf3fa4147ffbea3fc0e38b22014';
var auth_token = ''; // not needed for most
var instaHTML;
var divId = '#instafeed';
jQuery.ajax({
type: "GET",
dataType: "jsonp",
cache: false,
url: "https://api.instagram.com/v1/tags/"+hashtag+"/media/recent?client_id="+clientId,
success: function(x) {
for (var i = 0; i < 25; i++) {
// GET THE PICTURE
// -- options are thumbnail and large - see object for more
var instaPicture = x.data[i].images.thumbnail.url;
if (x.data[i].user.username == username) {
instaHTML += "<div class='CaroselSlideItem'><img src='" + instaPicture + "'/></div>";
}
// INSERT THE GALLERY
jQuery(divId).html(instaHTML);
}
}
});
You can console it via jQuery('body').html(instaHTML);
My error is
TypeError: x.data[i]
is undefined Line 707 in var instaPicture = x.data[i].images.thumbnail.url;
Upvotes: 0
Views: 1198
Reputation: 388316
If x.data
has less than 25 results the error could come. Assume x.data
has only 20 results then when the loop reaches i=20
, x.data[i]
will be undefined.
So
jQuery.ajax({
type: "GET",
dataType: "jsonp",
cache: false,
url: "https://api.instagram.com/v1/tags/" + hashtag + "/media/recent?client_id=" + clientId,
success: function (x) {
for (var i = 0; i < x.data.length && i < 25; i++) {
// GET THE PICTURE
// -- options are thumbnail and large - see object for more
var instaPicture = x.data[i].images.thumbnail.url;
if (x.data[i].user.username == username) {
instaHTML += "<div class='CaroselSlideItem'><img src='" + instaPicture + "'/></div>";
}
// INSERT THE GALLERY
jQuery(divId).html(instaHTML);
}
}
});
Upvotes: 1