Getting Youtube view counts for several videos using APIv3 (jquery) - javascript

I'm trying to create a youtube social feed that includes the video, title, description, date, and view count. I've got everything to work except for the last one, view count. I've been able to get the view counts to show up but they are always out of order and I'm lost on how to make them match up to their respective videos. I used this video as an initial tutorial: [https://www.youtube.com/watch?v=jdqsiFw74Jk][1] It got me this far, but now I'm lost again. Here is my code via code pen: [http://codepen.io/ThatsMyJams/pen/EjZWex][2]
here is my html:
<div id="container">
<h2>Results:</h2>
<ul id="results"></ul>
</div>
and here is my javascript:
var yourApiKey = 'AIzaSyDpY9FHgp7EvnDr5mGrxWwKgUBtfM8l5PE';
var channelName = 'GoogleDevelopers';
var vidCount = 5;
var vidHeight = 275;
var vidWidth = 400;
$(document).ready(function(){
$.get(
"https://www.googleapis.com/youtube/v3/channels", {
part: 'contentDetails',
forUsername: channelName,
key: yourApiKey},
function(data){
$.each(data.items, function(i, item){
console.log(item);
playerID = item.contentDetails.relatedPlaylists.uploads;
getVids(playerID);
})
}
);
function getVids() {
$.get(
"https://www.googleapis.com/youtube/v3/playlistItems", {
part: 'snippet',
maxResults: vidCount,
playlistId: playerID,
key: 'AIzaSyDpY9FHgp7EvnDr5mGrxWwKgUBtfM8l5PE'},
function(data){
var output;
$.each(data.items, function(i, item){
console.log(item);
vidTitle = item.snippet.title;
videoID = item.snippet.resourceId.videoId;
vidDate = item.snippet.publishedAt;
vidDesc = item.snippet.description;
output = '<li>'+vidTitle+'<span class="date">'+vidDate+'</span><p class="description">'+vidDesc+'</p><iframe height="'+vidHeight+'" width ="'+vidWidth+'" src=\"//www.youtube.com/embed/'+videoID+'\"></iframe></li>';
//append to results list
$('#results').append(output);
getViews(videoID[i]);
})
}
);
}
function getViews() {
$.get(
"https://www.googleapis.com/youtube/v3/videos", {
part: 'statistics',
id: videoID,
key: 'AIzaSyDpY9FHgp7EvnDr5mGrxWwKgUBtfM8l5PE'},
function(data){
var output2;
$.each(data.items, function(i, item){
vidViews = item.statistics.viewCount;
output2 = '<span class="views">'+vidViews+'</span>'
//append to results list
$('#results li').each(function() {
$(this).append(output2);
});
})
}
);
}
});
I just want to get the viewCount for each video and insert it into the html much like I did for the title, date, etc. Any help would be greatly appreciated :)

Here's your modified code. this will display views at the end of each video:
var yourApiKey = 'AIzaSyDpY9FHgp7EvnDr5mGrxWwKgUBtfM8l5PE';
var channelName = 'GoogleDevelopers';
var vidCount = 5;
var vidHeight = 275;
var vidWidth = 400;
$(document).ready(function () {
$.get(
"https://www.googleapis.com/youtube/v3/channels", {
part: 'contentDetails',
forUsername: channelName,
key: yourApiKey
},
function (data) {
$.each(data.items, function (i, item) {
console.log(item);
playerID = item.contentDetails.relatedPlaylists.uploads;
getVids(playerID);
})
}
);
function getVids() {
$.get(
"https://www.googleapis.com/youtube/v3/playlistItems", {
part: 'snippet',
maxResults: vidCount,
playlistId: playerID,
key: 'AIzaSyDpY9FHgp7EvnDr5mGrxWwKgUBtfM8l5PE'
},
function (data) {
var output;
$.each(data.items, function (i, item) {
console.log(item);
vidTitle = item.snippet.title;
videoID = item.snippet.resourceId.videoId;
vidDate = item.snippet.publishedAt;
vidDesc = item.snippet.description;
var viewCountId = "viewCount" + i;
output = '<li>' + vidTitle + '<span class="date">' + vidDate + '</span><p class="description">' + vidDesc + '</p><iframe height="' + vidHeight + '" width ="' + vidWidth
+ '" src=\"//www.youtube.com/embed/' + videoID + '\"></iframe>"<span id="' + viewCountId + '"></span></li>';
//append to results list
$('#results').append(output);
getViews(viewCountId);
})
}
);
}
function getViews(viewCountId) {
$.get(
"https://www.googleapis.com/youtube/v3/videos", {
part: 'statistics',
id: videoID,
key: 'AIzaSyDpY9FHgp7EvnDr5mGrxWwKgUBtfM8l5PE'
},
function (data) {
var output2;
$.each(data.items, function (i, item) {
$('#'+viewCountId).text("views=" + item.statistics.viewCount);
})
}
);
}
});

Related

YouTube API --- next video autoplay?

I have a YouTube API working for fetching and listing to video, when user clicks on thumbnail they get the video autoplay perfectly, but I would like when the first video is finished, the next video from my list autoplays also.
I've looked on Stack Overflow but haven't found one that fits my needs. Here is the code:
// Searchbar Handler
$(function () {
var searchField = $('#query');
var icon = $('#search-btn');
// Focus Event Handler
$(searchField).on('focus', function () {
$(this).animate({
width: '100%' },
400);
$(icon).animate({
right: '10px' },
400);
});
// Blur Event Handler
$(searchField).on('blur', function () {
if (searchField.val() == '') {
$(searchField).animate({
width: '45%' },
400, function () {});
$(icon).animate({
right: '360px' },
400, function () {});
}
});
$('#search-form').submit(function (e) {
e.preventDefault();
});
});
function search() {
// Clear Results
$('#results').html('');
$('#buttons').html('');
// Get Form Input
q = $('#query').val();
// Run GET Request on API********************************
$.get(
"https://www.googleapis.com/youtube/v3/search?maxResults=**", {
part: 'snippet, id',
q: q+'********',
fs:1,
hd:1,
type: 'video',
videoCategoryId :'***',
key: 'your api key' },
function (data) {
var nextPageToken = data.nextPageToken;
var prevPageToken = data.prevPageToken;
// Log Data
console.log(data);
$.each(data.items, function (i, item) {
// Get Output****
var output = getOutput(item);
// Display Results*****
$('#results').append(output);
});
var buttons = getButtons(prevPageToken, nextPageToken);
// Display Buttons
$('#buttons').append(buttons);
});
}
///////////////////////////////////////////////////////////////
// Next Page Function
function nextPage() {
var token = $('#next-button').data('token');
var q = $('#next-button').data('query');
// Clear Results
$('#results').html('');
$('#buttons').html('');
// Get Form Input
q = $('#query').val();
// Run GET Request on API
$.get(
"https://www.googleapis.com/youtube/v3/search?maxResults=***", {
part: 'snippet, id',
q: '***********',
fs:1,
hd:1,
pageToken: token,
type: 'video',
videoCategoryId : '*****',
key: 'your api key' },
function (data) {
var nextPageToken = data.nextPageToken;
var prevPageToken = data.prevPageToken;
// Log Data
console.log(data);
$.each(data.items, function (i, item) {
// Get Output
var output = getOutput(item);
// Display Results
$('#results').append(output);
});
var buttons = getButtons(prevPageToken, nextPageToken);
// Display Buttons
$('#buttons').append(buttons);
});
}
// Prev Page Function
function prevPage() {
var token = $('#prev-button').data('token');
var q = $('#prev-button').data('query');
// Clear Results
$('#results').html('');
$('#buttons').html('');
// Get Form Input
q = $('#query').val();
// Run GET Request on API
$.get(
"https://www.googleapis.com/youtube/v3/search?maxResults=***", {
part: 'snippet, id',
q: **********,
fs:1,
hd:1,
pageToken: token,
type: 'video',
videoCategoryId : '*****',
key: 'your api key' },
function (data) {
var nextPageToken = data.nextPageToken;
var prevPageToken = data.prevPageToken;
// Log Data
console.log(data);
$.each(data.items, function (i, item) {
// Get Output
var output = getOutput(item);
// Display Results
$('#results').append(output);
});
var buttons = getButtons(prevPageToken, nextPageToken);
// Display Buttons
$('#buttons').append(buttons);
});
}
// Build Output**********************************************
function getOutput(item) {
var videoId = item.id.videoId;
var title = item.snippet.title.substring(0, 33);
/*var description = item.snippet.description.substring(0, 20);*/
var thumb = item.snippet.thumbnails.high.url;
var channelTitle = item.snippet.channelTitle;
var videoDate = item.snippet.publishedAt;
// Build Output String**************************************
var output = '<li>' +
'<a target="mainVid" href="https://www.youtube.com/embed/' + videoId + '/?autoplay=1&modestbranding=1&rel=0"><img src="' + thumb + '"></a>' +
'<h3><a target="mainVid" href="https://www.youtube.com/embed/' + videoId + '/?autoplay=1&modestbranding=1&rel=0">' + title + '</a></h3>' +
'<p>' + '</p>' +
'</li>' +
'<div class="clearfix"></div>' +
'';
return output;
}
// Build the buttons
function getButtons(prevPageToken, nextPageToken) {
if (!prevPageToken) {
var btnoutput = '<div class="button-container">' + '<button id="next-button" class="btn btn-primary" data-token="' + nextPageToken + '" data-query="' + q + '"' +
'onclick="nextPage();">Page Suiv</button></div>';
} else {
var btnoutput = '<div class="button-container">' +
'<button id="prev-button" class="btn btn-primary" data-token="' + prevPageToken + '" data-query="' + q + '"' +
'onclick="prevPage();">Page Préc</button>' +
'<button id="next-button" class="btn btn-primary" data-token="' + nextPageToken + '" data-query="' + q + '"' +
'onclick="nextPage();">Page Suiv</button></div>';
}
return btnoutput;
}
I know I need a function on an event but I don't know which one and where to place it.
have a look at this post Play next youtube src when the other one is finished Here is explained that you will need to use the youtube iFrame API (shared earlier) to be able to access the player events. This post also mentions in the post How to detect when a youtube video finishes playing? Here is a working example shared from 2012.
I don't write Javascript or have ever written something with the youtube API so I cannot give you a working example. But I'm sure with these posts and API docs you can find the answer you are seeking.
ok hi everyone !!!
here the solution with fancy box : add data-fancybox="video" on link to open
and give some instructions :
$('[data-fancybox]').fancybox({
infobar: false,
buttons: false,
afterLoad: function (instance, current) {
if (instance.group.length > 1 && current.$content) {
current.$content.append('<a data-fancybox-next class="button-next" href="javascript:;">→</a><a data-fancybox-previous class="button-previous" href="javascript:;">←</a>');
}
current.$content.append('<a data-fancybox-close class="button-close" href="javascript:;">×</a>');
} });
});
work very fine !!!!
thank for your help ...

delete from database with javascript

I added a delete function to a todo list app that i built. The delete function works; however, when I refresh the page all the items that i deleted come back. How can I remove the items permanently from the database?
$(function() {
// The taskHtml method takes in a JavaScript representation
// of the task and produces an HTML representation using
// <li> tags
function taskHtml(task) {
var checkedStatus = task.done ? "checked" : "";
var liClass = task.done ? "completed" : "";
var liElement = '<li id="listItem-' + task.id +'" class="' + liClass + '">' +
'<div class="view"><input class="toggle" type="checkbox"' +
" data-id='" + task.id + "'" +
checkedStatus +
'><label>' +
task.title +
// '<button class="deletebutton" type="button">Delete</button>' +
'</label></div></li>';
return liElement;
}
// toggleTask takes in an HTML representation of the
// an event that fires from an HTML representation of
// the toggle checkbox and performs an API request to toggle
// the value of the `done` field
function toggleTask(e) {
var itemId = $(e.target).data("id");
var doneValue = Boolean($(e.target).is(':checked'));
$.post("/tasks/" + itemId, {
_method: "PUT",
task: {
done: doneValue
}
}).success(function(data) {
var liHtml = taskHtml(data);
var $li = $("#listItem-" + data.id);
$li.replaceWith(liHtml);
$('.toggle').change(toggleTask);
} );
}
$.get("/tasks").success( function( data ) {
var htmlString = "";
$.each(data, function(index, task) {
htmlString += taskHtml(task);
});
var ulTodos = $('.todo-list');
ulTodos.html(htmlString);
$('.toggle').change(toggleTask);
});
$('#new-form').submit(function(event) {
event.preventDefault();
var textbox = $('.new-todo');
var payload = {
task: {
title: textbox.val()
}
};
$.post("/tasks", payload).success(function(data) {
var htmlString = taskHtml(data);
var ulTodos = $('.todo-list');
ulTodos.append(htmlString);
$('.toggle').click(toggleTask);
$('.new-todo').val('');
});
});
//////this section works
$("#deletebutton").on("click", function() {
$(".todo-list li.completed").remove()
///////this does not want to remove the item from the database
$.destroy("/tasks/" + itemId, {
_method: "destroy",
task: {
done: doneValue
}
});
});
$(function() {
// The taskHtml method takes in a JavaScript representation
// of the task and produces an HTML representation using
// <li> tags
function taskHtml(task) {
var checkedStatus = task.done ? "checked" : "";
var liClass = task.done ? "completed" : "";
var liElement = '<li id="listItem-' + task.id +'" class="' + liClass + '">' +
'<div class="view"><input class="toggle" type="checkbox"' +
" data-id='" + task.id + "'" +
checkedStatus +
'><label>' +
task.title +
// '<button class="deletebutton" type="button">Delete</button>' +
'</label></div></li>';
return liElement;
}
// toggleTask takes in an HTML representation of the
// an event that fires from an HTML representation of
// the toggle checkbox and performs an API request to toggle
// the value of the `done` field
function toggleTask(e) {
var itemId = $(e.target).data("id");
var doneValue = Boolean($(e.target).is(':checked'));
// still dont understand this
$.post("/tasks/" + itemId, {
_method: "PUT",
task: {
done: doneValue
}
}).success(function(data) {
var liHtml = taskHtml(data);
var $li = $("#listItem-" + data.id);
$li.replaceWith(liHtml);
$('.toggle').change(toggleTask);
} );
}
$.get("/tasks").success( function( data ) {
var htmlString = "";
$.each(data, function(index, task) {
htmlString += taskHtml(task);
});
var ulTodos = $('.todo-list');
ulTodos.html(htmlString);
$('.toggle').change(toggleTask);
});
$('#new-form').submit(function(event) {
event.preventDefault();
var textbox = $('.new-todo');
var payload = {
task: {
title: textbox.val()
}
};
$.post("/tasks", payload).success(function(data) {
var htmlString = taskHtml(data);
var ulTodos = $('.todo-list');
ulTodos.append(htmlString);
$('.toggle').click(toggleTask);
$('.new-todo').val('');
});
});
$("#deletebutton").on("click", function() {
$(".todo-list li.completed").remove()
var li_to_delete = $('.todo-list li.completed');
$.ajax({
type: 'DELETE',
url: "/tasks" + li_to_delete,
success: function(){
li_to_delete.remove();
}
});
});
});
i changed the code but im not sure how to properly extract the url.

Youtube API Get each playlist and its containing videos from channel

I'm trying to create a list of Youtube playlists and each list item to contain the playlist's videos as well.
Something like this (this would be a playlist section):
The issue I'm having is when calling the requestVideoPlaylist function inside the renderPlaylistSection I get undefined. However, if I call the requestVideoPlaylist with a given playlistId outside of the render... function the result gets returned correctly.
Please find my code on the following lines.
I've also made a reproduction on JSFiddle
// Retrieve the list of playlists
function requestPlaylists(channelId) {
playlistsContainer.html('');
var requestOptions = {
channelId: channelId,
part: 'snippet,contentDetails',
maxResults: 4
}
var request = gapi.client.youtube.playlists.list(requestOptions);
request.execute(function(response) {
var playlists = response.result.items;
if (playlists) {
$.each(playlists, function(index, item) {
renderPlaylistSection(playlistsContainer, item.id, item.snippet);
});
} else {
playlistsContainer.html('Sorry, you have no uploaded videos');
}
});
}
// Retrieve the list of videos in the specified playlist.
function requestVideoPlaylist(playlistId, pageToken) {
var requestOptions = {
playlistId: playlistId,
part: 'snippet,contentDetails',
maxResults: 5
};
if (pageToken) {
requestOptions.pageToken = pageToken;
}
var request = gapi.client.youtube.playlistItems.list(requestOptions);
request.execute(function(response) {
// Only show pagination buttons if there is a pagination token for the
// next or previous page of results.
nextPageToken = response.result.nextPageToken;
var nextVis = nextPageToken ? 'visible' : 'hidden';
$('.js-next-videos').css('visibility', nextVis);
prevPageToken = response.result.prevPageToken
var prevVis = prevPageToken ? 'visible' : 'hidden';
$('.js-prev-videos').css('visibility', prevVis);
var playlistItems = response.result.items;
if (playlistItems) {
$.each(playlistItems, function(index, item) {
if (this.snippet.thumbnails) {
renderVideoItem(item.snippet);
}
});
}
});
}
// Render playlist section
function renderPlaylistSection(container, playlistId, playlistSnippet) {
var title = playlistSnippet.title;
container.append(
'<div class="playlist"><h3>Playlist Title: ' + title + '</h3>' +
'<div class="row playlist-videos">' + requestVideoPlaylist(playlistId) + '</div></div>'
);
}
function renderVideoItem(videoSnippet) {
var title = videoSnippet.title;
var thumbnail = videoSnippet.thumbnails.medium.url;
return (
'<div class="thumb" style="overflow: hidden;">' +
'<img src="' + thumbnail + '">' +
'</div>'
);
}

Repeated video duration values in asnyc to videoId - Youtube API v3

I'm having a problem with the asynchronous methods that prints and returns all vidDuration values then viewCount values were placed for each videoId, but vidDuration repeated only the last value that was received and assigned it to all of the videoIds which is clearly wrong.
I tried setting up a temporary array called tempArray within the loop that store each of the vidDuration values which it did, then to print them to each vidDuration, but then again, it looped through the output however many values are in the array and duplicated the videos, which I don't want. I commented out lines involving tempArray and reverted back to the working problem.
From what I understand, the async methods printed all of the duration values without going to the output as if it got stuck there until it was done and resolved and then it looped the viewCount and output perfectly fine. I'm wondering how do I fix this in a programmatically logical way?
Script:
var channelName = 'ExampleChannel';
var vidWidth = 500;
var vidHeight = 400;
var vidResults = 15; /* # of videos to show at once - max 50 */
var vidDuration = "";
var viewCount = 0;
var videoId = "";
$(document).ready(function() {
$.get( // get channel name and load data
"https://www.googleapis.com/youtube/v3/channels",
{
part: 'contentDetails',
forUsername: channelName,
key: 'XXXXXXXX'
},
function(data)
{
$.each(data.items,
function(i, item) {
console.log(item); // log all items to console
var playlistId = item.contentDetails.relatedPlaylists.uploads;
getPlaylists(playlistId);
})
}
);
// function that gets the playlists
function getPlaylists(playlistId)
{
$.get(
"https://www.googleapis.com/youtube/v3/playlistItems",
{
part: 'snippet',
maxResults: vidResults,
playlistId: playlistId,
key: 'XXXXXXXX'
},
// print the results
function(data)
{
var output;
/*var tempArray = new Array();*/ // temporary array for storing video duration values
$.each(data.items,
function(i, item) {
console.log(item);
var vidTitle = item.snippet.title; // video title
var vidDesc = item.snippet.description; // video description
var videoId = item.snippet.resourceId.videoId; // video id
// check if description is empty
if(vidDesc == null || vidDesc == "")
{
vidDesc = "No description was written."; // FIX: test msg to see where it still shows up
$('#desc').remove(); // remove video description
}
else vidDesc = item.snippet.description;
getVideoDuration(videoId).done(function(r){
vidDuration = r;
console.log(r);
/*tempArray[i] = r;*/ // store value into each array index
/*console.log("Array:", tempArray[i], tempArray);*/ // log to console
/*i++;*/ // increment
getViewCount(videoId).done(function(r){
viewCount = r;
console.log(r);
//vidDuration = getVideoDuration(videoId);
//viewCount = getViewCount(videoId);
// temp array index to loop thru array
/*$.each(tempArray, function(i){
vidDuration = tempArray[i]; // assign index value to vidDuration
console.log("In Each vidDuration: ", vidDuration);
i++;
});*/
console.log("id: " + videoId + " duration: " + vidDuration + " viewCount: " + viewCount); // return value in console
output = '<li><iframe height="' + vidHeight + '" width="' + vidWidth + '" src=\"//www.youtube.com/embed/' + videoId + '\"></iframe></li><div id="title">' + vidTitle + '</div><div id="desc">' + vidDesc + '</div><div id="duration">Length: ' + vidDuration + '</div><div id="stats">View Count: ' + viewCount + '</div>';
// Append results to list tag
$('#results').append(output);
}); // end of getVideoDuration(videoId).done
}); // end of getViewCount(videoId).done
});
/*console.log("TEMPARRAY[]",tempArray);*/ // print entire array
}
);
}
// return video duration
function getVideoDuration(videoId)
{
var defer1 = $.Deferred();
var r = '';
$.get(
"https://www.googleapis.com/youtube/v3/videos",
{
part: 'contentDetails',
id: videoId,
key: 'XXXXXXXX',
},
function(data)
{
$.each(data.items,
function(i, item) {
r = item.contentDetails.duration;
defer1.resolve(r);
console.log("in vidDuration func", r);
});
}
);
return defer1.promise();
}
// return video view count
function getViewCount(videoId)
{
var defer2 = $.Deferred();
var r = '';
$.get(
"https://www.googleapis.com/youtube/v3/videos",
{
part: 'contentDetails, statistics',
id: videoId,
key: 'XXXXXXXX',
},
function(data)
{
$.each(data.items,
function(i, item) {
r = item.statistics.viewCount;
defer2.resolve(r);
console.log("in viewCount func", r);
});
}
);
return defer2.promise();
}
});
Screenshot results (normal refresh):
Screenshot results (using debugger):
Here's a screenshot of the results when stepping through with the debugger console. (Why are the results different from when the page normally loads? Is this typical action of the async methods? How do I fix this?)
In fact the second promise is misplaced, the second promise is resolved AFTER that all the promises from the first promise have been resolved, so the last value is save. logical
Now if you resolve the first promise WHEN second is resolved one by one you are able to correct the problem.
var view = 0;
r = item.contentDetails.duration; // video duration
getViewCount(videoId).done(function(t){
view = t;
dfrd1.resolve(r, view);
});
Check the screenshot:
I change a bit the code to solve the problem.
var channelName = 'example';
var vidWidth = 500;
var vidHeight = 400;
var vidResults = 15; /* # of videos to show at once - max 50 */
var vidDuration = "";
var viewCount = 0;
var videoId = "";
$(document).ready(function() {
$.get( // get channel name and load data
"https://www.googleapis.com/youtube/v3/channels",
{
part: 'contentDetails',
forUsername: channelName,
key: 'xxx'
},
function(data)
{
$.each(data.items,
function(i, item) {
//console.log(item); // log all items to console
var playlistId = item.contentDetails.relatedPlaylists.uploads;
//var viewCount = console.log(item.statistics.viewCount);
getPlaylists(playlistId);
});
}
);
// function that gets the playlists
function getPlaylists(playlistId)
{
$.get(
"https://www.googleapis.com/youtube/v3/playlistItems",
{
part: 'snippet',
maxResults: vidResults,
playlistId: playlistId,
key: 'xxx'
},
// print the results
function(data)
{
var output;
$.each(data.items,
function(i, item) {
console.log(item);
var vidTitle = item.snippet.title; // video title
var vidDesc = item.snippet.description; // video description
var videoId = item.snippet.resourceId.videoId; // video id
// check if description is empty
if(vidDesc == null || vidDesc == "")
{
vidDesc = "No description was written."; // FIX: test msg to see where it still shows up
$('#desc').remove(); // remove video description
}
else vidDesc = item.snippet.description;
getVideoDuration(videoId).done(function(d, v){
vidDuration = d;
//console.log(r);
viewCount = v;
document.write("id: " + videoId + " duration: " + vidDuration + " viewCount: " + viewCount); // return value in console
document.write("<br>");
output = '<li><iframe height="' + vidHeight + '" width="' + vidWidth + '" src=\"//www.youtube.com/embed/' + videoId + '\"></iframe></li><div id="title">' + vidTitle + '</div><div id="desc">' + vidDesc + '</div><div id="duration">Length: ' + vidDuration + '</div><div id="stats">View Count: ' + viewCount + '</div>';
// Append results to list tag
$('#results').append(output);
});
});
}
);
}
// return video duration
function getVideoDuration(videoId)
{
var dfrd1 = $.Deferred();
var r = '';
$.get(
"https://www.googleapis.com/youtube/v3/videos",
{
part: 'contentDetails',
id: videoId,
key: 'xxx',
},
function(data)
{
$.each(data.items,
function(i, item) {
//videoId = item.snippet.resourceId.videoId;
var view = 0;
r = item.contentDetails.duration; // video duration
getViewCount(videoId).done(function(t){
view = t;
dfrd1.resolve(r, view);
});
//alert(videoId);
});
}
);
return dfrd1.promise();
}
// return video view count
function getViewCount(videoId)
{
var dfrd2 = $.Deferred();
var r = '';
$.get(
"https://www.googleapis.com/youtube/v3/videos",
{
part: 'contentDetails, statistics',
id: videoId,
key: 'xxx',
},
function(data)
{
$.each(data.items,
function(i, item) {
//videoId = item.snippet.resourceId.videoId;
r = item.statistics.viewCount; // view count
//alert(videoId);
dfrd2.resolve(r);
// console.log("in", r);
});
}
);
return dfrd2.promise();
}
});

How to get video duration and how to get only music videos via YouTube Api V3

how to use part : snippet and contentDetails ?? i want to get duration,only music videos,title and watched count..
please help me.
function keyWordsearch() {
gapi.client.setApiKey("MY_API_KEY");
gapi.client.load('youtube', 'v3', function () {
var q = $('#query').val();
$("#result").empty();
var request = gapi.client.youtube.search.list({
q: q,
part: 'snippet',
maxResults: 5,
});
request.execute(function (response) {
for (var i = 0; i < response.items.length; i++) {
var id = response.items[i].id.videoId;
var name = response.items[i].snippet.title;
$('#result').html($('#result').html() + "<li><a href='http://www.youtube.com/watch?v=" + id + "'>" + name + " </a></li>");
}
$('#result').html($('#result').html() + '</ul>');
});
});
}
</script>
<script src="https://apis.google.com/js/client.js?onload=onLoadCallback"></script>
i write console.log(response.items[i].snippet) then result is like this

Categories

Resources