MeltingDog
MeltingDog

Reputation: 15424

Tumblr API getting 'Uncaught TypeError: Cannot read property 'type' of undefined'

I have a series of Tumblr feeds on my site, each retrieving posts from a different tag.

The first feed script works but the 2nd and 3rd throw the error:

Uncaught TypeError: Cannot read property 'type' of undefined

Each script is exactly the same accept for the tag retrieve and the element the data it is appended to.

I am having trouble figuring this out. Does anyone know what I've done wrong?

$.ajax({
    url: "http://api.tumblr.com/v2/blog/myblog.tumblr.com/posts?api_key=mykey&tag=news",
    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 == "text") {
         var title = results.response.posts[i].title;
         var content = results.response.posts[i].body;
         $("#tumnews #newscara").append("<div class='tumpost'><a href='" + link + "'><h2>" + title + "</h2>" + content + "</a></div>");
       }
       else if (type == "photo") {
         var photourl = results.response.posts[i].photos[0].alt_sizes[0].url;
         $("#tumnews #newscara").append("<li><div class='tumpost'><a href='" + link + "'><img src='" + photourl + "' alt='" + title + "'/></a></div></li>");
       }

      i++;
     }//END WHILE


  $("#newscara").flexisel({
    visibleItems: 5,
    animationSpeed: 200,
    autoPlay: true,
    autoPlaySpeed: 3000,
    pauseOnHover: true,
    clone:false,
  });

    }//END RESULTS FUNCTION
});

Upvotes: 0

Views: 5313

Answers (1)

MeltingDog
MeltingDog

Reputation: 15424

I found the error was becuase there were fewer posts in the other two tags I was retrieving, and because I specified while (i < 10) it kept looping through and if there were less then 10 posts the error would appear.

I ammended it by replacing the while statement with

while (i < results.response.posts.length)

so it would only loop through the amount of posts that actually existed.

Upvotes: 3

Related Questions