I’m trying to use the youtube api to get playlist items. There are more than 50 in the list so will need to build a loop to get them. When a button is clicked I’m calling a function that will return 50 at a time then will build a loop to get all items.
Having problems returning the nextpagetoken from the function. I couldn’t figure out a way to return the data so got to a point where I’ve just plugged the nextpagetoken into the html of a div inside the function but, once the function finishes when I try to get the html value it returns blank.
The console.log('Nextpagetoken: ’ + data.nextPageToken); command shows the correct value.
The console.log('After call: ’ + next); command shows a blank value.
Also, the ‘After call’ command appears in the console log before the ‘Nextpagetoken’ log.
Any help greatly received. Here’s the javascript and html:
$(document).ready(function()
{
var loop=0;
var data;
var next='';
$('#get').click(function(){
getVids();
next=$('#pagetoken').text();
console.log('After call: ' + next);
});
function getVids(page){
$('#results').html("");
data = {
part: 'snippet',
maxResults: 50,
playlistId: 'playlist',
key: 'myKey',
pageToken: page
};
$.get(
"https://www.googleapis.com/youtube/v3/playlistItems", data,
function(data){
var output;
console.log('Page: ' + data.nextPageToken);
$.each(data.items, function(i, item)
{
console.log(item);
videoTitle = item.snippet.title;
rvideoID = item.snippet.resourceId.videoId;
vidThumburl = item.snippet.thumbnails.high.url;
output = '<li style="list-style:none;">' + rvideoID + ' <a class="videos2 video" href="https://www.youtube.com/watch?v=' + rvideoID + '">' + videoTitle + '<a/></li>';
//Append to results list
$('#results').append(output);
});
console.log('Nextpagetoken: ' + data.nextPageToken);
$('#pagetoken').html(data.nextPageToken);
});
}
});
Here’s the html:
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
<title>Untitled Document</title>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.3/jquery.min.js"></script>
<link href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/css/bootstrap.min.css" rel="stylesheet" integrity="sha384-BVYiiSIFeK1dGmJRAkycuHAHRg32OmUcww7on3RYdg4Va+PmSTsz/K68vbdEjh4u" crossorigin="anonymous">
<script src="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/js/bootstrap.min.js" integrity="sha384-Tc5IQib027qvyjSMfHjOMaLkfuWVxZxUPnCJA7l2mCWNIpG9mGCD8wGNIcPD7Txa" crossorigin="anonymous"></script>
<script src="yt.js"></script>
</head>
<body>
<div id="container">
<button id='get' type="button" class="btn btn-primary">Go</button>
<ul id="results"></ul>
<div id='pagetoken'></div>
</div>
</div>
</body>