Reputation: 15424
I am trying to implement a photo feed using the Tumblr API. So far it works with just text, but when I try photos I get the error
Cannot read property 'alt_sizes' of undefined
I am not sure how to go about correcting my code to fix this. My code is:
$.ajax({
url: "http://api.tumblr.com/v2/blog/myblog.tumblr.com/posts?api_key=key&tag=offers",
dataType: 'jsonp',
success: function(results){
var i = 0;
while (i < 10) {
var type = results.response.posts[i].type;
var date = results.response.posts[i].date;
var link = results.response.posts[i].post_url;
if (type == "photo") {
var photourl = results.response.posts[i].photos[i].alt_sizes[i].url;
$("#tumoffers").append("<div class='tumpost'><a href='" + link + "'><img src='" + photourl + "' alt='" + title + "'/></a></div>");
}
i++;
}//END WHILE
}//END RESULTS FUNCTION
});
Looking at the Tumblr API documentation I see that alt_sizes
translates to the size of the image, but I dont want to use this attribute.
Does anyone know how to make the API ignore this property?
Upvotes: 1
Views: 302
Reputation: 15424
I found it was getting an error because you can have multiple photos per post, so the lines
.photos[i].alt_sizes[i]
are actually in a different array, within the main posts array.
In my case I was only using 1 photo per post, so I simply changed it to
.photos[0].alt_sizes[0]
but to do it correctly you should create another loop for the photos per post.
Upvotes: 1
Reputation: 100175
you could use hasOwnProperty to check if such property exists before actually trying to access it, like:
var data = results.response,
i = results.response.total_posts; //this gives total posts you have
while (i < 10) {
var type = data.posts[i].type,
date = data.posts[i].date,
link = data.posts[i].post_url;
if( "photo" == type ) {
if( data.posts[i].hasOwnProperty("alt_sizes") {
var photourl = results.response.posts[i].photos[i].alt_sizes[i].url;
$("#tumoffers").append("<div class='tumpost'><a href='" + link + "'><img src='" + photourl + "' alt='" + title + "'/></a></div>");
}
}
i++;
}
Upvotes: 1