lharby lharby - 4 months ago 18
Ajax Question

Tumblr API get last 50 photo posts in large sizes not quite working

I have something very close to what I need, but I must be missing something.

Here is my code:

$.ajax({
url: "http://api.tumblr.com/v2/blog{my-blog}/posts?limit=50",
dataType: 'jsonp',
data: {
api_key: "{my key}"
},
success: function(results){
console.log(results);
var i = 0;

while (i < 50) {

var type = results.response.posts[i].type;
console.log(results.response.posts.length);

if (type == "photo") {
var getImages = results.response.posts[i].photos[i].alt_sizes[0].url;
$("#tumblr-posts").append("<div class='postbody'>" + "<img src=" + getImages + " /></div>");
}
i++;
}
}
});


This is returning the first image from my blog in the large size, but I am also getting an error in the console: Cannot read property 'alt_sizes' of undefined. I've tried a few variations but buy my logic the loop should return all posts .posts[i], all photos .photos[i] and then the first image in the array of alt_sizes[0] which should be the large image.

The console is showing that 50 objects are being returned so the call to the API is OK.

Any help much appreciated.

Answer

You are using the counter i to select the specific properties of posts and photos, which is why it returns undefined, for example:

i = 1;
var getImages = results.response.posts[1].photos[1].alt_sizes[0].url;

posts[1] is the second post in the response, but photos[1] refers to the second photo of posts[1] and probably doesn't exist as its a single photo post.

You need to create another loop to check for more than one photo per post, photosets will have up to ten photos.

var i = 0;

while (i < 50) {

  var type = results.response.posts[i].type;

  if (type == "photo") {

    var photos = results.response.posts[i].photos;

    for (var j = 0; j < photos.length; j++) {
      console.log( photos[j].alt_sizes[0].url );
    }

  }

  i++;

}   

Its also worth mentioning that on older images, if there is no high resolution version available, it doesn't fall back to another URL, its left blank, so you may need to check for that as well.