Related Videos with part contentDetails and Statistics - Youtube API V3 - javascript

I'm having a problem with retrieving related videos as thumbnails towards a specific video. In my code, I have the search->list set up correctly and returns the different titles and thumbnail URLs for the related videos. However, since search->list doesn't have parameter contentDetails or statistics, I found another question related to my exact same problem here and used a secondary call for getting videos->list since it supports those parameters to be able to retrieve the duration and view count. But the problem is that both values (vidDuration & viewCount) are not being passed anything and marked as undefined as the item is passed through it and halted. How can I make the item's duration and viewCount values based on search->list's item?
script.js:
function relatedVids(videoId)
{
debugger;
$.get( // get related videos related to videoId - relatedToVideoId
"https://www.googleapis.com/youtube/v3/search",
{
part: 'snippet',
maxResults: vidResults,
relatedToVideoId: videoId, // $.cookie("id"); from single-video.html
type: 'video',
key: 'XXXXXXXXX'
},
function(data)
{
$.each(data.items,
function(i, item)
{
console.log(item);
var vidTitle = item.snippet.title; // video title
//var videoId = item.snippet.resourceId.videoId; // video id
//var vidDuration = item.contentDetails.duration;
//var viewCount = item.statistics.viewCount;
var vidThumbUrl = item.snippet.thumbnails.default.url; // video thumbnail url
var extractVideoId = null; // var to extract video id string from vidThumbUrl
// check if vidThumbUrl is not null, empty string, or undefined
if(vidThumbUrl)
{
//console.log("vidThumbUrl: ", vidThumbUrl);
var split = vidThumbUrl.split("/"); // split string when '/' seen
extractVideoId = split[4]; // retrieve the fourth index on the fourth '/'
//console.log("extractVideoId: ", extractVideoId); // YE7VzlLtp-4
//console.log("split array: ", split);
}
else console.error("vidThumbUrl is either undefined or null or empty string.");
// if video title is longer than 25 characters, insert the three-dotted ellipse
if(vidTitle.length > 25)
{
var strNewVidTitle = vidTitle.substr(0, 25) + "...";
vidTitle = strNewVidTitle;
}
// search->list only takes snippet, so to get duration and view count; have to call this function that has the recognized param structure
$.get(
"https://www.googleapis.com/youtube/v3/videos",
{
part: 'contentDetails, statistics',
id: extractVideoId, //item.snippet.resourceId.videoId,
key: 'XXXXXXXXX',
},
// return search->list item's duration and view count
function(item)
{
vidDuration = item.contentDetails.duration; // pass item's duration
return vidDuration;
},
function(item)
{
viewCount = item.statistics.viewCount; // pass item's view count
return viewCount;
}
);
try
{
var vidThumbnail = '<div class="video-thumbnail"><a class="thumb-link" href="single-video.html"><div class="video-overlay"><img src="imgs/video-play-button.png"/></div><img src="' + vidThumbUrl + '" alt="No Image Available." style="width:204px;height:128px"/></a><p><a class="thumb-link" href="single-video.html">' + vidTitle + '</a><br/>' + convert_time(vidDuration) + ' / Views: ' + viewCount + '</p></div>';
// print results
$('.thumb-related').append(vidThumbnail);
}
catch(err)
{
console.error(err.message); // log error but continue operation
}
}
);
}
);
}
single-video.html script:
$(document).ready(function()
{
var videoId;
$(function()
{
if($.cookie("title") != null && $.cookie("id") != null)
{
var data = '<div class="video"><iframe height="' + vidHeight + '" width="' + vidWidth + '" src=\"//www.youtube.com/embed/' + $.cookie("id") + '\"></iframe></div><div class="title">' + $.cookie("title") + '</div><div class="desc">' + $.cookie("desc") + '</div><div class="duration">Length: ' + $.cookie("dur") + '</div><div class="stats">View Count: ' + $.cookie("views") + '</div>';
$("#video-display").html(data);
$("#tab1").html($.cookie("desc"));
videoId = $.cookie("id");
//vidDuration = $.cookie("dur"); works but prints out the same value for each
//viewCount = $.cookie("views"); works but prints out the same value for each
debugger;
relatedVids(videoId); // called here
console.log("from single-vid.html globalPlaylistId: ", $.cookie("playlistId"));
// remove cookies after transferring it to this page for display
$.removeCookie("title");
$.removeCookie("id");
$.removeCookie("desc");
$.removeCookie("views");
$.removeCookie("dur");
$.removeCookie("tags");
$.removeCookie("playlistId");
}
});
});

You're referring the item in the search results.
When you issued a get request to videos, you will get a response of video contentDetails and statistics. Apparently, you didn't capture the returned response.
$.get(
"https://www.googleapis.com/youtube/v3/videos",
{
part: 'contentDetails, statistics',
id: videoId, //item.snippet.resourceId.videoId,
key: 'XXXXXXXXX',
},
function(videoItem)
{
vidDuration = videoItem.contentDetails.duration; // pass item's duration
viewCount = videoItem.statistics.viewCount; // pass item's view count
}
);
NOTE: You can pass a string of video IDs delimited by a comma to fetch multiple video contentDetails/statistics in one request.

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

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();
}
});

Changing the objectId thats returned in a query to that of the actual user

Using parse.com and JavaScript SDK.
This is what I'm attempting to achieve.
A list of users (friends) is returned on the page to the user, They can then click on one of these users and the page is updated to list all of that users items (which are basically images).
This query works correctly and returns a list of users.
var currentUser = Parse.User.current();
var FriendRequest = Parse.Object.extend("FriendRequest");
var query = new Parse.Query(FriendRequest);
query.include('toUser');
query.include('SentTo');
query.include("myBadge");
query.equalTo("fromUser", currentUser);
query.equalTo("status", "Request sent");
query.find({
success: function (results) {
var friends = [];
for (var i = 0; i < results.length; i++) {
friends.push({
imageURL: results[i].get('toUser').get('pic'),
friendRequestId: results[i].id,
username: results[i].get('toUser').get('username')
});
}
// TW: replaced dynamic HTML generation with wrapper DIV that contains IMG and name DIV
_.each(friends, function (item) {
// using a wrapper so the user can click the pic or the name
var wrapper = $('<div class="wrapper" data-friend-request-id="' + item.friendRequestId + '"></div>');
wrapper.append('<img class="images" src="' + item.imageURL + '" />');
wrapper.append('<div>' + item.username + '</div>');
$('#container').append(wrapper);
});
},
error: function (error) {
alert("Error: " + error.code + " " + error.message);
}
});
****This below query should contain the user who has selected above and stored in window.selectedFriendRequestId (which is saved in the variable friendRequest ****
This query looks at the myBadges class and the user reference "SentTo" the ref used is for example a3aePaphBF which is the actual _User objectID.
function FriendProfile() {
var friendRequest = "window.selectedFriendRequestId";
console.log(window.selectedFriendRequestId);
var myBadges = Parse.Object.extend("myBadges");
var query = new Parse.Query(myBadges);
query.equalTo("SentTo", friendRequest);
query.find({
success: function (results) {
// If the query is successful, store each image URL in an array of image URL's
imageURLs = [];
for (var i = 0; i < results.length; i++) {
var object = results[i];
imageURLs.push(object.get('BadgeName'));
}
// If the imageURLs array has items in it, set the src of an IMG element to the first URL in the array
for (var j = 0; j < imageURLs.length; j++) {
$('#imgs').append("<img src='" + imageURLs[j] + "'/>");
}
},
error: function (error) {
// If the query is unsuccessful, report any errors
alert("Error: " + error.code + " " + error.message);
}
});
}
The issue is that the first query is not returning an objectId that I can use in the second query as a reference. For example a3aePaphBF is not returned but cr3LG70vrF is.
How to I return the actual _User objectid in the first query so I can make these match?
To get the ID of a user:
results[i].get('toUser').id
So if you update your section of code that is doing friends.push(...):
friends.push({
imageURL: results[i].get('toUser').get('pic'),
friendRequestId: results[i].id,
username: results[i].get('toUser').get('username'),
userId: results[i].get('toUser').id
});
Then in your bit where you create the wrapper:
_.each(friends, function (item) {
// using a wrapper so the user can click the pic or the name
var wrapper = $('<div class="wrapper"'
+ ' data-friend-request-id="' + item.friendRequestId + '"'
+ ' data-to-user-id="' + item.userId + '"></div>');
wrapper.append('<img class="images" src="' + item.imageURL + '" />');
wrapper.append('<div>' + item.username + '</div>');
$('#container').append(wrapper);
});
Notice that I've added another data-property to hold the ID of the toUser.
Now if you followed the tips from your other question, you can tweak the code that attaches the on-click handler to pass toUserId also:
$('#container').on('click', '.wrapper', function () {
var wrapper = $(this);
var friendRequestId = wrapper.data('friendRequestId');
var toUserId = wrapper.data('toUserId');
FriendProfile(friendRequestId, toUserId);
// other code ...
});
Lastly your FriendProfile() function can now use either of those parameters as needed:
function FriendProfile(friendRequestId, toUserId) {
var toUser = new Parse.User();
toUser.id = toUserId;
var myBadges = Parse.Object.extend("myBadges");
var query = new Parse.Query(myBadges);
query.equalTo("SentTo", toUser);
// ... etc ...
}
NOTE: The User class should be locked down for privacy reasons, you shouldn't be able to read any properties of other users except in Cloud Code when you have the following line in your Cloud Function:
Parse.Cloud.useMasterKey();

Generating a CSV with JavaScript works but I am getting an empty trailing column

I've written some scripts to convert the pagination (20 photos per ajax request) from instagram json feeds to csv for easily storing the photo urls in our database. Our CMS is automatically able to convert CSV files into SQl files either by replacing the table or by appending to it. The problem is it will only work if ALL of the columns are the same.
It's close to totally working but I can't import my generated csvs because they keep getting an empty column where it should be line breaking to a new row because the final CSV output contains a comma + line break when it should only be returning the line break (i.e. without a trailing comma).
Encoding is UTF-8 and line breaks are being added using "\n". I've tried console logging just about every step of the process and it seems that there that
Here's a picture of one of the CSVs I am generating: http://screencast.com/t/dZfqN08A
Below is all the relevant code:
First I'm using ajax with a jsonp callback to load instagram photos based on a hashtag.
Photos are loaded like this:
function loadNext(nextUrl) {
$.ajax({
url: url,
cache: false,
type: 'POST',
dataType: "jsonp",
success: function(object) {
console.log('loadmore');
if (object) {
console.log(object);
$('.loadmore').fadeOut(500);
// chargement photos gallerie
$.each( object.data, function(home, photo) {
photo = '<div class="photo photo-load">' +
'<img class="pull-me" src="' + photo.images.low_resolution.url + '" height="380px" width="380px" alt="photo">' +
'<div class="dot"></div>' +
'<div class="share" >' +
'<!-- AddThis Button BEGIN -->' +
'<div class="addthis_toolbox addthis_default_style addthis_16x16_style">' +
'<a class="addthis_button_twitter"></a>' +
'<a class="addthis_button_facebook"></a>' +
'</div>' +
'<!-- AddThis Button END -->' +
'</div>' +
'<div class="text-photo">' +
'<div class="svg line w-line"></div>' +
'<h4 class="left">'+ photo.user.username + '</h4>' +
'<h4 class="right share-photo">PARTAGE</h4>' +
'</div>' +
'<div class="vote w-path-hover">' +
'<div class="fb-like" data-href="http://dev.kngfu.com/maurice/" data-layout="box_count" data-action="like" data-show-faces="false" data-share="false"></div>' +
'<div class="insta-like">' +
'<div class="count-box">' +
'<p>'+ photo.likes.count + '</p>' +
'</div>' +
'<a class="insta-button" title="Pour appuyer votre proposition préférée, rendez-vous sur Instagram." href="http://instagram.com/" ><i class="fa fa-instagram"></i>J aime</a>' +
'</div> ' +
'<div class="w-path"></div>' +
'<div class="base-cross"></div>' +
'<h4 class="vote-button">VOTE</h4>' +
'</div>' +
'</div>';
$(photo).appendTo( $( ".gallery" ) );
});
url = object.pagination.next_url;
console.log(url);
} else {
console.log("error");
}
} // end success func.
});
}
Then in a separate ajax call I can convert the same json feed to a csv file using this function (this function also calls a couple other functions so the dependent functions are included below the ajax call):
function convertJSON (nextUrl) {
$.ajax({
url: url,
cache: false,
type: 'POST',
dataType: "jsonp",
success: function(object) {
if (object) {
console.log(object);
var fromJSON = new Array();
i = 0;
$.each( object.data, function(home, photo) {
i++;
var photopath = photo.images.low_resolution.url;
var postID = photo.id;
var userID = photo.user.id;
var user = photo.user.username;
// watch out for those wild fullnames in instagram json
var fullname = photo.user.full_name;
fullname = fullname.replace(/[^a-z0-9]+|\s+/gmi, " ");
//console.log(fullname);
var likes = photo.likes.count;
var winner = 0;
var winnerplace = " ";
var campaign = "maurice1";
var timestamp = photo.created_time;
// easydate field formatting
var date = new Date();
date.setSeconds( timestamp );
var photodeleted = 0;
// add new rows to csv
var linebreak = "\n";
var arrayFromJSON = new Array( linebreak+photopath,
postID,
userID,
user,
fullname,
likes,
winner,
winnerplace,
campaign,
timestamp,
date,
photodeleted );
fromJSON[i] = arrayFromJSON.join();
});
//url = object.pagination.next_url;
//console.log(url);
//console.log( fromJSON );
makeCSV( fromJSON );
} else {
console.log("error");
}
} // end success func.
});
}
// json to csv converter
function makeCSV (JSONData) {
//console.log("makeCSV() function was started");
var data = encodeURIComponent(JSONData);
var currentTime = new Date().getTime();
var date = getDate( currentTime );
//console.log(JSONData);
var fileName = date;
var uri = "data:text/csv;charset=utf-8," // sets mime/data type
+ "photopath," // now 12 strings which are the CSV's column titles
+ "postid,"
+ "userid,"
+ "username,"
+ "fullname,"
+ "likes,"
+ "winner,"
+ "winnerplace,"
+ "campaign,"
+ "creationdate,"
+ "easydate,"
+ "photodeleted"
+ data; // finally append our URI encoded data
console.log(uri);
// generate a temp <a /> tag that will auto start our download when the function is called
var link = document.createElement("a");
link.id = new Date().getTime();
link.href = uri;
// link visibility hidden
link.style = "visibility:hidden";
link.download = fileName + ".csv";
// append anchor tag and click
$("div#hidden").append(link);
link.click();
//document.body.removeChild(link);
}
// this function just makes human readable dates for CSV filename and id of our link tag
function getDate() {
var date = new Date();
//zero-pad a single zero if needed
var zp = function (val){
return (val <= 9 ? '0' + val : '' + val);
}
//zero-pad up to two zeroes if needed
var zp2 = function(val){
return val <= 99? (val <=9? '00' + val : '0' + val) : ('' + val ) ;
}
var d = date.getDate();
var m = date.getMonth() + 1;
var y = date.getFullYear();
var h = date.getHours();
var min = date.getMinutes();
var s = date.getSeconds();
var ms = date.getMilliseconds();
return '' + y + '-' + zp(m) + '-' + zp(d) + ' ' + zp(h) + 'h' + zp(min) + 'm' + zp(s) + 's';
}
From all the console logging I've done, I can definitely assure you that I'm getting no trailing comma until the final step where the json array data gets URI encoded.
Since this extra column is also included in the header row I'm wondering if it has to do with this line?
var uri = "data:text/csv;charset=utf-8," // sets mime/data type
I've also tried ISO-8859-1 encoding but I get the same result.
Does anyone know why this is happening? Any help would be appreciated
Your passing an array of lines to encodeURIComponent. That will stringify the array, joining it with a comma - which you don't want.
What you should do is
var arrayFromJSON = new Array( photopath,
// remove linebreak here ^
postID,
userID,
user,
fullname,
likes,
winner,
winnerplace,
campaign,
timestamp,
date,
photodeleted );
fromJSON[i] = arrayFromJSON.join(",");
// make comma explicit: ^^^
…
makeCSV( fromJSON );
…
var data = encodeURIComponent(JSONData.join("\n"));
// join the lines by a linebreak: ^^^^
…
var uri = "data:text/csv;charset=utf-8," // sets mime/data type
+ "photopath," // now 12 strings which are the CSV's column titles
+ "postid,"
+ "userid,"
+ "username,"
+ "fullname,"
+ "likes,"
+ "winner,"
+ "winnerplace,"
+ "campaign,"
+ "creationdate,"
+ "easydate,"
+ "photodeleted"
+ "\n"
// ^^^^^^ add linebreak
+ data; // finally append our URI encoded data

Categories

Resources