title: Using YouTube API to get all comments from a video with the JSON feed
body: <p>I'm using the YouTube API to get comments for a video with a parameterized query like the following:</p>
  
  <p><code>http://gdata.youtube.com/feeds/api/videos/theVideoID/comments?v=2&amp;alt=json</code></p>
  
  <p>The problem with this is that the maximum number of results you can get per query is 50. I want to get every comment. I'm currently using the <code>start-index</code> and <code>max-results</code> parameters to solve this. I had a bit of trouble doing iterations of 50 at a time because sometimes the iteration would have a start-index above the number of comments and I couldn't figure that out, so I just tried to work out one at a time. It may be better to do 50 at a time, so let me know if that is the better solution. For now:</p>
  
  <p>I'm using PHP to get the amount of comments:</p>
  
  <pre><code>&lt;?php
      $video_ID = 'gT2HYxOdxUk';
      $JSON = file_get_contents("https://gdata.youtube.com/feeds/api/videos/{$video_ID}?v=2&amp;alt=json");
      $JSON_Data = json_decode($JSON);
      $commentCount = $JSON_Data-&gt;{'entry'}-&gt;{'gd$comments'}-&gt;{'gd$feedLink'}-&gt;{'countHint'};
  ?&gt;
  </code></pre>
  
  <p>And then I'm calling a JavaScript/jQuery function to load all comments into an array. For testing, it prints them into a div. For starters, here's how I'm calling the function:</p>
  
  <pre><code>&lt;body onLoad="loadComments('&lt;?php echo $commentCount; ?&gt;', '&lt;?php echo $video_ID; ?&gt;')"&gt;
  </code></pre>
  
  <p>Next, the actual function:</p>
  
  <pre><code>function loadComments(count, videoID) {     
      for(i = 1; i &lt;= count; i++) {
          $.ajax({
              url: "http://gdata.youtube.com/feeds/api/videos/" + videoID + "/comments?v=2&amp;alt=json&amp;max-results=1" + "&amp;start-index=" + i,
              dataType: "jsonp",
              success: function(data){
                  $.each(data.feed.entry, function(key, val) {
                      comments.push(val.content.$t);
                      $('#commentOutput').append(val.content.$t + '&lt;br&gt;'); //Just for testing purposes.
                  });
              }
  
          });
      }
  }
  </code></pre>
  
  <p>The problem is that it is really iffy. When I use the <code>count</code> variable as the terminating part of the for loop like this, it always gets like, for example, 45 out of 211 comments. If I manually enter 211, it will go to around 195. If I put in a low number, like 1-15, it pretty much always gets them all. 20+, it's never right.</p>
  
  <p>I need to figure out how to get this to consistently get all the comments of a given video by taking advantage of the <code>max-results</code> and <code>start-index</code> parameters. Thanks!</p>