Search code examples
javascriptajaxapitumblr

Tumblr API: 'Cannot read property 'alt_sizes' of undefined'


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?


Solution

  • 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.