Hi I want to show only the first video in iframe while other in thumbnail.
Here is my code you can run it on localhost.If you have any solution then please reply me.
index.php file
<!DOCTYPE html>
<!--
To change this license header, choose License Headers in Project Properties.
To change this template file, choose Tools | Templates
and open the template in the editor.
-->
<html>
<head>
<meta charset="UTF-8">
<title>youtube Channel Videos</title>
<style>
body{
background: #f4f4f4;
font-family: "Arial" sans-serif;
font-size: 14px;
color: #666;
}
#container{
width: 800px;
overflow: auto;
margin: auto;
background: #fff;
padding: 15px;
}
.anc{
padding: 2px 6px;
background: #EFF7FF;
color: #069;
border: 1px solid #C2D9EF;
margin: 0px 0px 0px 5px;
-moz-border-radius: 1px;
-webkit-border-radius: 1px;
text-decoration: none;
text-align: center;
}
</style>
<!-- <link rel="stylesheet" href="http://maxcdn.bootstrapcdn.com/bootstrap/3.3.5/css/bootstrap.min.css">-->
<script src="js/jquery.min.js"></script>
<script type="text/javascript" src="http://www.youtube.com/player_api"></script>
<!-- <script src="http://maxcdn.bootstrapcdn.com/bootstrap/3.3.5/js/bootstrap.min.js"></script>-->
<script src="js/script.js"></script>
</head>
<body>
<?php
// put your code here
?>
<div id="container">
<h1>Youtube Videos</h1>
<ul id="results">
</ul>
<div id="page" style="padding-top: 15px;padding-left: 42px;"></div>
</div>
<script>
players = new Array();
//alert($("iframe.yt_players"));
function onYouTubeIframeAPIReady() {
var temp = $("iframe.yt_players");
for (var i = 0; i < temp.length; i++) {
var t = new YT.Player($(temp[i]).attr('id'), {
events: {
'onStateChange': onPlayerStateChange
}
});
players.push(t);
}
}
window.onload = setTimeout(onYouTubeIframeAPIReady, 10000);
function onPlayerStateChange(event) {
if (event.data == YT.PlayerState.PLAYING) {
var temp = event.target.a.src;
var tempPlayers = $("iframe.yt_players");
for (var i = 0; i < players.length; i++) {
if (players[i].a.src != temp) players[i].stopVideo();
}
}
}
</script>
</body>
</html>
script.js file
function tplawesome(template, data) {
// initiate the result to the basic template
res = template;
// for each data key, replace the content of the brackets with the data
for(var i = 0; i < data.length; i++) {
res = res.replace(/\{\{(.*?)\}\}/g, function(match, j) { // some magic regex
return data[i][j];
});
}
return res;
}
var channelName= "TechGuyWeb";
$(document).ready(function(){
$.get("https://www.googleapis.com/youtube/v3/channels",{
part: 'contentDetails',
forUsername: channelName,
key:'AIzaSyBX94DoCYdtIwALVPfqSVar6izj3wCJ1M4'},
function(data){
console.log(data);
$.each(data.items,function(i, item){
var pid = item.contentDetails.relatedPlaylists.uploads;
//console.log(pid);
getVids(pid);
});
}
);
//var pid="10thStreetPreschool";
// function getvids(pid){
// $.get("https://www.googleapis.com/youtube/v3/playlistItems",{
// part: 'snippet',
// maxResults: 10,
// playlistId:pid,
// key:'AIzaSyBX94DoCYdtIwALVPfqSVar6izj3wCJ1M4'},
// function(data){
// var output;
// $.each(data.items,function(i, item){
// console.log(data);
// var v_id = item.snippet.resourceId.videoId;
// //alert(item.snippet.resourceId.videoId);
// //var video_title = item.snippet.title;
// //output= '<li>'+video_title+'</li>';
// $.get("item.html",function(data){
// $('#results').append(tplawesome(data, [{"title":item.snippet.title,"videoid":item.snippet.resourceId.videoId,"description":item.snippet.description}]));
// getcount(v_id);
// });
// //$('#results').append(output);
// });
// }
// );
// }
function getVids(pid, pageToken){
var data = {
part: 'snippet',
maxResults: 10,
playlistId: pid,
key: 'AIzaSyBX94DoCYdtIwALVPfqSVar6izj3wCJ1M4'
}
try{
if(pageToken){
data["pageToken"] = pageToken;
}
}catch(err){
}
$.get(
"https://www.googleapis.com/youtube/v3/playlistItems", data,
function(data){
var output;
$('#results').html("");
$.each(data.items,function(i, item){
console.log(data);
var v_id = item.snippet.resourceId.videoId;
// var total_results =data.pageInfo.totalResults;
// console.log(total_results);
$.get("item.html",function(data){
$('#results').append(tplawesome(data, [{"title":item.snippet.title,"videoid":item.snippet.resourceId.videoId,"description":item.snippet.description}]));
getcount(v_id);
});
//$('#results').append(output);
});
$('#page').html("");
try{
if(data.prevPageToken){
$("#page").append('<span><a class="anc" href="javascript:void(0);" onclick="getVids(\'' + pid + '\', \'' + data.prevPageToken + '\');">« Previous<a/></span>');
}
}catch(err){
}
try{
if(data.nextPageToken){
$("#page").append('<span><a class="anc" href="javascript:void(0);" onclick="getVids(\'' + pid + '\', \'' + data.nextPageToken + '\');">Next »<a/></span>');
}
}catch(err){
}
});
}
function getcount(v_id){
$.get("https://www.googleapis.com/youtube/v3/videos",{
part: 'statistics',
id: v_id,
key:'AIzaSyBX94DoCYdtIwALVPfqSVar6izj3wCJ1M4'},
function(data){
$.each(data.items,function(i, item){
var views = item.statistics.viewCount;
//console.log(views);
$('#'+v_id).append(views);
});
}
);
}
});
function getVids(pid, pageToken){
var data = {
part: 'snippet',
maxResults: 10,
playlistId: pid,
key: 'AIzaSyBX94DoCYdtIwALVPfqSVar6izj3wCJ1M4'
}
try{
if(pageToken){
data["pageToken"] = pageToken;
}
}catch(err){
}
$.get(
"https://www.googleapis.com/youtube/v3/playlistItems", data,
function(data){
var output;
$('#results').html("");
$.each(data.items,function(i, item){
console.log(data);
var v_id = item.snippet.resourceId.videoId;
//alert(item.snippet.resourceId.videoId);
//var video_title = item.snippet.title;
//output= '<li>'+video_title+'</li>';
$.get("item.html",function(data){
$('#results').append(tplawesome(data, [{"title":item.snippet.title,"videoid":item.snippet.resourceId.videoId,"description":item.snippet.description}]));
getcount(v_id);
});
//$('#results').append(output);
});
$('#page').html("");
try{
if(data.prevPageToken){
$("#page").append('<span><a class="anc" href="javascript:void(0);" onclick="getVids(\'' + pid + '\', \'' + data.prevPageToken + '\');">« Previous<a/></span>');
}
}catch(err){
}
try{
if(data.nextPageToken){
$("#page").append('<span><a class="anc" href="javascript:void(0);" onclick="getVids(\'' + pid + '\', \'' + data.nextPageToken + '\');">Next »<a/></span>');
}
}catch(err){
}
});
}
function getcount(v_id){
$.get("https://www.googleapis.com/youtube/v3/videos",{
part: 'statistics',
id: v_id,
key:'AIzaSyBX94DoCYdtIwALVPfqSVar6izj3wCJ1M4'},
function(data){
$.each(data.items,function(i, item){
var views = item.statistics.viewCount;
console.log(views);
$('#'+v_id).append(views);
});
}
);
}
item.html file
<div class="item" style="padding-bottom: 30px;">
<iframe id="player{{videoid}}" class="yt_players" src="http://www.youtube.com/embed/{{videoid}}?rel=0&enablejsapi=1;showinfo=0;&wmode=Opaque" width="560" height="315" frameborder="0" allowfullscreen></iframe>
<div style="margin-bottom: -22px;margin-top: -20px;"><h2 style="font-size:18px;">{{title}}</h2></div>
<div style="margin-bottom: -18px;"><h5 style="font-size:16px;">{{description}}</h5> </div>
<div><h5 style="font-size:14px;margin-top: -5px;">Total Views: <span id="{{videoid}}"></span></h5> </div>
</div>
Related
I have an HTML form within a Web App, created with GAS.
This HTML form was created from this file upload script here:
drive-multi-upload
This is the HTML form:
The point is that I needed the files to be uploaded in folders that follow the following pattern:
The first number refers to the model selected on the form, the second number refers to the slot used.
Therefore, it was necessary to create a function to identify the input chosen in the Model and, according to this input, check which is the first empty folder, then take the ID of that folder and pass it to the client side to upload the file inside it.
With the help of some members of the community, some adaptations were made and the final function was this:
/** Modified version of script written by Tanaike */
function createOrGetFolder(folderName, parentFolderId) {
try {
var parentFolder = DriveApp.getFolderById(parentFolderId), folder;
if (parentFolder) {
var foldersIter = parentFolder.getFoldersByName("Video");
if (foldersIter.hasNext()) {
var videoFolder = foldersIter.next();
var nextFolderName = folderName + "-01";
while (!folder) {
video_folder = videoFolder.getFoldersByName(nextFolderName);
if (video_folder.hasNext()) {
folder = video_folder.next();
var files = folder.getFiles();
if (files.hasNext()) {
var [a, b] = nextFolderName.split("-");
nextFolderName = `${a}-${String(Number(b) + 1).padStart(2, "0")}`;
folder = null;
}
} else {
folder = videoFolder.createFolder(nextFolderName);
}
}
} else {
folder = parentFolder.createFolder("Video");
folder = folder.createFolder(folderName);
}
} else {
throw new Error("Parent Folder with id: " + parentFolderId + " not found");
}
return folder.getId();
} catch (error) {
return error;
}
}
It works perfectly, the point is that this form also has a function that generates a .csv file when the form is submitted, the function is this one:
.gs file:
const saveDataAsCSV = (data, folderId) => DriveApp.getFolderById(folderId).createFile("Sample.csv", data);
HTML file:
var name = $('#name01').val();
var description = $('#description').val();
var model = $('#Model').val();
upload_folder = model;
var color = $('#Color').val();
var form_values = [name, description, model, color];
var data = form_values.join(",");
google.script.run.saveDataAsCSV(data, uploadParentFolderId);
My goal is to make the .csv file be generated with the same name as the folder where the file was uploaded, that is, if the file is uploaded in folder 01-01, the file name has to be 01-01.csv, if the file is uploaded in the 02-02 folder, the file name has to be 02-02.csv, and so on.
How can I achieve this?
The complete script code can be viewed here:
.gs file:
function doGet(e) {
return HtmlService.createTemplateFromFile('forms0101.html').evaluate();
}
function getOAuthToken() {
return ScriptApp.getOAuthToken();
}
function getParent(){
var ss = SpreadsheetApp.getActiveSpreadsheet();
var id = ss.getId();
var parent = DriveApp.getFileById(id).getParents().next().getId();
return parent
}
function getLimitFolder(){
var ss = SpreadsheetApp.getActiveSpreadsheet();
var pastapai = DriveApp.getFileById(ss.getId()).getParents();
var limitfolder = pastapai.next().getFoldersByName("_").next().getId();
return limitfolder;
}
function getFilesLimit(){
var ss = SpreadsheetApp.getActiveSpreadsheet();
var pastapai = DriveApp.getFileById(ss.getId()).getParents();
var files = [];
Logger.log(pastapai);
//var limitfolder = pastapai.next().getFoldersByName("_").next().getId();
var limitfolder = pastapai.next().getFoldersByName("_").next().getFiles();
while(limitfolder.hasNext()){
var file = limitfolder.next();
files.push([file.getId()]);
}
console.log(files.length);
return files.length;
}
//function testenumeroarquivos(){
//console.log(checkForFiles()); // When you use this line, you can see the filename of the files.
//}
/**
* creates a folder under a parent folder, and returns it's id. If the folder already exists
* then it is not created and it simply returns the id of the existing one
*/
function createOrGetFolder(folderName, parentFolderId) {
try {
var parentFolder = DriveApp.getFolderById(parentFolderId), folder;
if (parentFolder) {
var foldersIter = parentFolder.getFoldersByName("Video");
if (foldersIter.hasNext()) {
var videoFolder = foldersIter.next();
var nextFolderName = folderName + "-01";
while (!folder) {
video_folder = videoFolder.getFoldersByName(nextFolderName);
if (video_folder.hasNext()) {
folder = video_folder.next();
var files = folder.getFiles();
if (files.hasNext()) {
var [a, b] = nextFolderName.split("-");
nextFolderName = `${a}-${String(Number(b) + 1).padStart(2, "0")}`;
folder = null;
}
} else {
folder = videoFolder.createFolder(nextFolderName);
}
}
} else {
folder = parentFolder.createFolder("Video");
folder = folder.createFolder(folderName);
}
} else {
throw new Error("Parent Folder with id: " + parentFolderId + " not found");
}
console.log("Test" + nextFolderName)
return folder.getId();
} catch (error) {
return error;
}
}
const saveDataAsCSV = (data, folderId) => {
const folder = DriveApp.getFolderById(folderId);
folder.createFile(`${nextFolderName.getName()}.csv`, data);
}
const increaseRequest = (data, folderId) => DriveApp.getFolderById(folderId).createFile("IncreaseRequest.csv", data);
// NOTE: always make sure we use DriveApp, even if it's in a comment, for google to import those
// libraries and allow the rest of the app to work. see https://github.com/tanaikech/Resumable_Upload_For_WebApps
HTML file:
<!DOCTYPE html>
<html>
<head>
<base target="_blank">
<meta name="viewport" content="width=device-width, initial-scale=1.0" />
<title>Drive Multi Large File Upload</title>
<link href="https://fonts.googleapis.com/icon?family=Material+Icons" rel="stylesheet">
<link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/materialize/0.97.5/css/materialize.min.css">
<!-- Bootstrap CSS -->
<link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/4.0.0/css/bootstrap.min.css" integrity="sha384-Gn5384xqQ1aoWXA+058RXPxPg6fy4IWvTNh0E263XmFcJlSAwiGgFAW/dAiS6JXm" crossorigin="anonymous">
<style>
#import url('https://fonts.googleapis.com/css2?family=Rubik:wght#400;600;700&display=swap');
.disclaimer{
width: 480px;
color: #646464;
margin: 20px auto;
padding:0 16px;
text-align:center;
font:400 12px Rubik,sans-serif;
}
h5.center-align.teal-text {
font:700 26px Rubik,sans-serif;
color: #00F498!important;
}
.row {
font:600 14px Rubik,sans-serif;
}
.btn {
background-color: black;
}
.btn:hover {
background-color: #00F498;
}
body {
margin-top: -40px;
}
#progress {
color: #00000;
}
.disclaimer a{
color: #00BCAA;
}
#credit{
display:none
}
.btnOpenModal {
font-size: x-large;
padding: 10px;
border: none;
border-radius: 5px;
background-color: blueviolet;
color: white;
cursor: pointer;
}
hr {
border: 0px;
border-top: 1px solid lightgray;
}
.modal-container {
width: 100vw;
position: fixed;
top: 30px;
display: none;
z-index: 999;
justify-content: center;
}
.modal {
display: flex;
flex-direction: column;
padding: 30px;
background-color: white;
border-radius: 10px;
width: 50%;
}
.active {
display: flex;
}
.active .modal {
animation: modal .4s;
}
#keyframes modal {
from {
opacity: 0;
transform: translate3d(0, -60px, 0);
}
to {
opacity: 1;
transform: translate3d(0, 0, 0);
}
}
.btns {
display: flex;
justify-content: space-between;
margin-top: 10px;
}
.btns button {
font-size: medium;
padding: 10px;
border: none;
border-radius: 5px;
color: white;
cursor: pointer;
}
.btnOK {
background-color: blue!important;
}
.btnClose {
background-color: brown!important;
}
</style>
</head>
<body>
<form class="main" id="form" novalidate="novalidate" style="max-width: 480px;margin: 40px auto;">
<div id="forminner">
<div class="modal-container">
<div class="modal">
<h2>Info</h2>
<hr />
<span>
Lorem Ipsum is simply dummy text of the printing and typesetting
industry. Lorem Ipsum has been the industry's standard dummy text
ever since the 1500s, when an unknown printer took a galley of
type and scrambled it to make a type specimen book.
</span>
<hr />
<div class="btns">
<button class="btnOK" onclick="increaseRequest(); closeModal();">OK</button>
<button class="btnClose" onclick="closeModal()">Close</button>
</div>
</div>
</div>
<h5 class="center-align teal-text" style="margin-bottom: -10px; font-size: 20px; font-family: Rubik; ">YOUR NAME</h5>
<div class="row">
<div class="input-field col s12">
<input id="name01" type="text" name="Name" class="validate" required="required" aria-required="true">
<label for="name" class="">Name</label>
</div>
</div>
<h5 class="center-align teal-text" style="margin-bottom: -10px; font-size: 20px; font-family: Rubik; ">SOME DESCRIPTION</h5>
<div class="row">
<div class="input-field col s12">
<input id="description" type="text" name="Description" class="validate" required="required" aria-required="true">
<label for="name">Description</label>
</div>
</div>
<div class="row">
<div class="col-8 col-md-4">
<h6>Model</h6>
<select class="custom-select" id="Model">
<option selected="">Choose...</option>
<option value="01">01</option>
<option value="02">02</option>
<option value="03">03</option>
</select>
<h6>Color</h6>
<select class="custom-select" id="Color">
<option selected="">Choose...</option>
<option value="Red">Red</option>
<option value="Green">Green</option>
</select>
</div>
</div>
<div class="row">
<div class="col s12">
<h5 class="center-align teal-text">Upload the Video File</h5>
</div>
</div>
<div class="row">
<div class="file-field input-field col s12">
<div id="input-btn" class="btn">
<span>File</span>
<input id="files" type="file" single="">
</div>
<div class="file-path-wrapper">
<input class="file-path validate" type="text" placeholder="Select the file">
</div>
</div>
</div>
<div class="row">
<div class="input-field col s6">
<button id="submit-btn" class="waves-effect waves-light btn submit-btn" type="submit" onclick="submitForm(); return false;">Submit</button>
</div>
</div>
<div class="row">
<div class="input-field col s12 hide" id="update">
<hr>
<p>
Por favor, aguarde enquanto seu arquivo está sendo carregado.<br><span style="color: #00000;"><b>Não feche ou atualize a janela durante o upload.</b></span>
</p>
</div>
</div>
<div class="row">
<div class="input-field col s12" id="progress">
</div>
</div>
</div>
</div>
<div id="success" style="display:none">
<h5 class="center-align teal-text">Tudo certo!</h5>
<p>Se você já preencheu todos os campos é só fechar essa janela e clicar em enviar!</p>
<button id="fechar" class="waves-effect waves-light btn submit-btn" style ="transform: translateX(160%);" type="button" onclick="google.script.host.close()">Fechar</button>
</div>
</form>
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/2.2.0/jquery.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/materialize/0.97.5/js/materialize.min.js"></script>
<script src="https://gumroad.com/js/gumroad.js"></script>
<script>
var upload_folder = "01";
const chunkSize = 5242880;
const uploadParentFolderId = <?=getParent()?>; // creates a folder inside of this folder
const limitfolder = <?=getLimitFolder()?>;
const fileslimit = <?=getFilesLimit()?>;
const modal = document.querySelector('.modal-container');
var name = $('#name01').val();
var description = $('#description').val();
var model = $('#Model').val();
upload_folder = model;
var color = $('#Color').val();
var form_values = [name, description, model, color];
form_values = form_values.map(r => r.replaceAll(",", "#")); // Essa linha substitui todas as "," por "#" antes de gerar o .csv
var data = form_values.join(",");
function submitForm() {
var name = $('#name01').val();
var description = $('#description').val();
var model = $('#Model').val();
upload_folder = model;
var color = $('#Color').val();
var form_values = [name, description, model, color];
form_values = form_values.map(r => r.replaceAll(",", "#")); // Essa linha substitui todas as "," por "#" antes de gerar o .csv
var data = form_values.join(",");
// Added the below script.
if ($('#submit-btn.disabled')[0]) return; // short circuit
var name = upload_folder
var files = [...$('#files')[0].files]; // convert from FileList to array
if (files.length === 0) {
showError("Por favor, selecione um arquivo");
return;
}
google.script.run.saveDataAsCSV(data, uploadParentFolderId);
google.script.run.saveDataAsCSV(data, limitfolder);
disableForm(); // prevent re submission
// the map and reduce are here to ensure that only one file is uploaded at a time. This allows
// the promises to be run sequentially
files.map(file => uploadFilePromiseFactory(file))
.reduce((promiseChain, currentTask) => {
return promiseChain.then(currentTask);
}, Promise.resolve([])).then( () => {
console.log("Completed all files upload");
showSuccess();
});
}
function checkforfiles() {
if (fileslimit <= 2) {
submitForm();
}
if (fileslimit == 3) {
openModal();
}
if (fileslimit >= 4) {
showError("erro");
return;
}
}
function openModal() {
modal.classList.add('active');
}
function closeModal() {
modal.classList.remove('active');
}
function increaseRequest() {
google.script.run.increaseRequest(data, limitfolder);
}
function disableForm() {
$('#submit-btn').addClass('disabled');
$('#input-btn').addClass('disabled');
$('#update').removeClass('hide');
$('#update').removeClass('hide');
}
function closer(){
google.script.host.close();
}
function uploadFilePromiseFactory(file) {
return () => {
console.log("Processing: ", file.name);
return new Promise((resolve, reject) => {
showProgressMessage("Seu arquivo está sendo carregado");
var fr = new FileReader();
fr.fileName = file.name;
fr.fileSize = file.size;
fr.fileType = file.type;
// not sure of a better way of passing the promise functions down
fr.resolve = () => resolve();
fr.reject = (error) => reject(error);
fr.onload = onFileReaderLoad;
fr.readAsArrayBuffer(file);
});
};
}
/**
* Gets called once the browser has loaded a file. The main logic that creates a folder
* and initiates the file upload resides here
*/
function onFileReaderLoad(onLoadEvent) {
var fr = this;
var newFolderName = upload_folder
createOrGetFolder(newFolderName, uploadParentFolderId).then(newFolderId => {
console.log("Found or created guest folder with id: ", newFolderId);
uploadFileToDriveFolder.call(fr, newFolderId).then(() => {
fr.resolve();
}, (error) => {
fr.reject(error);
});
},
(error) => {
if (error) {
showError(error.toString());
}
console.log("onFileReaderLoad Error2: ", error);
});
}
/**
* call to the DriveApp api. Wrapped in a promise in case I want to address timing issues between a
* createFolder and findFolderById
*/
function createOrGetFolder(folderName, parentFolderId) {
return new Promise((resolve, reject) => {
google.script.run.withSuccessHandler(response => {
console.log("createOrGetFolder response: ", response);
if (response && response.length) {
resolve(response);
}
reject(response);
}).createOrGetFolder(folderName, parentFolderId);
});
}
/**
* Helper functions modified from:
* https://github.com/tanaikech/Resumable_Upload_For_WebApps
*/
function uploadFileToDriveFolder(parentFolderId) {
var fr = this;
return new Promise((resolve, reject) => {
var fileName = fr.fileName;
var fileSize = fr.fileSize;
var fileType = fr.fileType;
console.log({fileName: fileName, fileSize: fileSize, fileType: fileType});
var buf = fr.result;
var chunkpot = getChunkpot(chunkSize, fileSize);
var uint8Array = new Uint8Array(buf);
var chunks = chunkpot.chunks.map(function(e) {
return {
data: uint8Array.slice(e.startByte, e.endByte + 1),
length: e.numByte,
range: "bytes " + e.startByte + "-" + e.endByte + "/" + chunkpot.total,
};
});
google.script.run.withSuccessHandler(oAuthToken => {
var xhr = new XMLHttpRequest();
xhr.open("POST", "https://www.googleapis.com/upload/drive/v3/files?uploadType=resumable");
xhr.setRequestHeader('Authorization', "Bearer " + oAuthToken);
xhr.setRequestHeader('Content-Type', "application/json");
xhr.send(JSON.stringify({
mimeType: fileType,
name: fileName,
parents: [parentFolderId]
}));
xhr.onload = () => {
doUpload(fileName, {
location: xhr.getResponseHeader("location"),
chunks: chunks,
}).then(success => {
resolve(success);
console.log("Successfully uploaded: ", fileName);
},
error => {
reject(error);
});
};
xhr.onerror = () => {
console.log("ERROR: ", xhr.response);
reject(xhr.response);
};
}).getOAuthToken();
});
}
function showSuccess() {
$('#forminner').hide();
$('#success').show();
$('#fechar').show();
}
function showError(e) {
$('#progress').addClass('red-text').html(e);
}
function showMessage(e) {
$('#update').html(e);
}
function showProgressMessage(e) {
$('#progress').removeClass('red-text').html(e);
}
/**
* Helper functions modified from:
* https://github.com/tanaikech/Resumable_Upload_For_WebApps
*/
function doUpload(fileName, e) {
return new Promise((resolve, reject) => {
showProgressMessage("Carregando: <span style='color: #00F498 ;'>" + "0%</span>");
var chunks = e.chunks;
var location = e.location;
var cnt = 0;
var end = chunks.length;
var temp = function callback(cnt) {
var e = chunks[cnt];
var xhr = new XMLHttpRequest();
xhr.open("PUT", location, true);
console.log("content range: ", e.range);
xhr.setRequestHeader('Content-Range', e.range);
xhr.send(e.data);
xhr.onloadend = function() {
var status = xhr.status;
cnt += 1;
console.log("Uploading: " + status + " (" + cnt + " / " + end + ")");
showProgressMessage("Carregando: <span style='color: #00F498 ;'>"
+ Math.floor(100 * cnt / end) + "%</span>" );
if (status == 308) {
callback(cnt);
} else if (status == 200) {
$("#progress").text("Done.");
resolve();
} else {
$("#progress").text("Error: " + xhr.response);
reject();
}
};
}(cnt);
});
}
/**
* Helper functions modified from:
* https://github.com/tanaikech/Resumable_Upload_For_WebApps
*/
function getChunkpot(chunkSize, fileSize) {
var chunkPot = {};
chunkPot.total = fileSize;
chunkPot.chunks = [];
if (fileSize > chunkSize) {
var numE = chunkSize;
var endS = function(f, n) {
var c = f % n;
if (c == 0) {
return 0;
} else {
return c;
}
}(fileSize, numE);
var repeat = Math.floor(fileSize / numE);
for (var i = 0; i <= repeat; i++) {
var startAddress = i * numE;
var c = {};
c.startByte = startAddress;
if (i < repeat) {
c.endByte = startAddress + numE - 1;
c.numByte = numE;
chunkPot.chunks.push(c);
} else if (i == repeat && endS > 0) {
c.endByte = startAddress + endS - 1;
c.numByte = endS;
chunkPot.chunks.push(c);
}
}
} else {
var chunk = {
startByte: 0,
endByte: fileSize - 1,
numByte: fileSize,
};
chunkPot.chunks.push(chunk);
}
return chunkPot;
}
</script>
</body>
</html>
It can also be viewed by accessing this worksheet
Although I'm not sure whether I could correctly understand your actual expected result, please test the following modification.
Google Apps Script side:
Please modify saveDataAsCSV of Google Apps Script as follows.
const saveDataAsCSV = (data, folderId1, folderId2 = null) => {
if (folderId2) {
DriveApp.getFolderById(folderId1).createFile(`${DriveApp.getFolderById(folderId2).getName()}.csv`, data);
} else {
DriveApp.getFolderById(folderId1).createFile("sample.csv", data);
}
}
Javascript side:
Please remove google.script.run.saveDataAsCSV(data, uploadParentFolderId); in the function submitForm.
And, please modify onFileReaderLoad of Javascript as follows.
function onFileReaderLoad(onLoadEvent) {
var fr = this;
var newFolderName = upload_folder
createOrGetFolder(newFolderName, uploadParentFolderId).then(newFolderId => {
google.script.run.saveDataAsCSV(data, uploadParentFolderId, newFolderId);
console.log("Found or created guest folder with id: ", newFolderId);
uploadFileToDriveFolder.call(fr, newFolderId).then(() => {
fr.resolve();
}, (error) => {
fr.reject(error);
});
},
(error) => {
if (error) {
showError(error.toString());
}
console.log("onFileReaderLoad Error2: ", error);
});
}
By this modification, I think that a CSV file like 01-01.csv is created to uploadParentFolderId folder.
I'm trying to display all the videos of a user YouTube channel, and in order to do so I'm trying to implement pagination with YouTube API. However, I'm having trouble storing the page tokens to every request.
var channelName = '*******';
var nextPageToken = "";
var prevPageToken = "";
var pid = "**********";
var counter;
begin();
function begin(){
$.get(
"https://www.googleapis.com/youtube/v3/channels",{
part: 'contentDetails',
forUsername: channelName,
key: '*********************'},
function(data){
$.each(data.items, function(i, item){
pid = item.contentDetails.relatedPlaylists.uploads;
getVids(pid);
})
}
);
}
function getVids(pid){
$.get(
"https://www.googleapis.com/youtube/v3/playlistItems",{
part: 'snippet',
maxResults: 50,
playlistId: pid,
key: '******************'},
function(data){
counter = data.pageInfo.totalResults;
var output;
nextPageToken = data.nextPageToken;
prevPageToken = data.prevPageToken;
$.each(data.items, function(i, item){
total = data.pageInfo.totalResults;
videoId = item.snippet.resourceId.videoId;
videoTitle = item.snippet.title;
videoImg = item.snippet.thumbnails.maxres.url;
output = `<div class="col-md-4" style="padding-bottom:1em;">
<div class="card" style="width: auto; border:none; border-radius:0%; background-image:url('${videoImg}');background-size: 100% 100%; background-repeat: no-repeat;">
<div class="card-body card-mod">
<p class="card-text" id="nombre-mod" style="text-align:left; font-weight:bold !important; color:#f2f2f2!important; font-size:20px; text-shadow: 2px 2px 5px #141313;">${videoTitle}</p>
</div>
</div>
</div>`;
//Append to results list
$('#results').append(output);
})
saveNext(nextPageToken);
for (i = 0; i < counter ; i++){
nextPage(pid,nextPageToken);
counter = counter - 50;
}
}
);
}
Here I try to store the nextPageToken value to pass it to new requests.
function saveNext(f){
nextPageToken = f;
return nextPageToken;
}
function nextPage(pid, nextPageToken){
$.get(
"https://www.googleapis.com/youtube/v3/playlistItems",{
part: 'snippet',
maxResults: 50,
playlistId: pid,
pageToken : nextPageToken,
key: 'AIzaSyCLj1raUEFRewglexWcIz5Z_roLYCAkpFw'},
function(data){
var output;
nextPageToken = data.nextPageToken;
saveNext(nextPageToken);
prevPageToken = data.prevPageToken;
$.each(data.items, function(i, item){
total = data.pageInfo.totalResults;
videoId = item.snippet.resourceId.videoId;
videoTitle = item.snippet.title;
videoImg = item.snippet.thumbnails.maxres.url;
output = `<div class="col-md-4" style="padding-bottom:1em;">
<div class="card" style="width: auto; border:none; border-radius:0%; background-image:url('${videoImg}');background-size: 100% 100%; background-repeat: no-repeat;">
<div class="card-body card-mod">
<p class="card-text" id="nombre-mod" style="text-align:left; font-weight:bold !important; color:#f2f2f2!important; font-size:20px; text-shadow: 2px 2px 5px #141313;">${videoTitle}</p>
</div>
</div>
</div>`;
$('#results').append(output);
})
}
);
}
So far I can only pass through one nextPageToken value to my requests and can't seem to store the next tokens on a playlist with almost 600 videos.
i just hit a demo api with link and created a dynamic table and in every click of parameter a new row is inserted with it, i just want to resitrict duplicate entry from table.
$(document).ready(function () {
//count = 1;
var counter=1,flag=0;
$("#api").click(function () {
var index = ($("#para").val());
if (index == "") {
alert("Please input data");
return false;
}
else{
$.ajax({
url: 'https://jsonplaceholder.typicode.com/todos/'+index,
type: 'GET',
dataType: 'json',
crossDomain: true,
success: function (data, textStatus, xhr) {
console.log(data);
var tr = [];
if(flag==0){
mytable = $('<table></table>').attr({ id: "basicTable", class:"basicTable1" });
//for (var i = 0; i < count; i++) {
let ab = $('<h1>API Data</h1>').appendTo("#h");
let row = $('<tr></tr>').appendTo(mytable);
let row1 = $('<tr id="row'+counter+'" ></tr>').appendTo(mytable);
$.each(data, function(key, val) {
$('<th></th>').text(key).appendTo(row);
$('<td></td>').text(val).appendTo(row1);
});
let row2 = $('<button class="button1" id="button'+ counter+'" onclick=removeFun('+ counter+')>remove Row</button>').appendTo(row1);
flag=1;
counter++;
//}
mytable.appendTo("#data");
}
else{
//for (var i = 0; i < count; i++) {
let row = $('<tr id="row'+counter+'" ></tr>').appendTo(mytable);
$.each(data, function(key, val) {
$('<td></td>').text(val).appendTo(row);
});
let row1 = $('<button class="button1" id="button'+ counter+'" onclick=removeFun('+ counter+')>remove Row</button>').appendTo(row);
counter++;
//}
mytable.appendTo("#data");
}
},
error: function (xhr, textStatus, errorThrown) {
console.log(errorThrown);
alert("No Record Found");
}
});
}
});
});
function removeFun(a){
$("#row"+a).remove();
}
var textbox = $("#data");
textbox.change(function() {
$("#basicTable").find("td").each(function(){
if($(this).html()==textbox.val()){
alert(textbox.val());
};
})
});
.h1{
color: orange;
margin:30px;
}
.h2{
margin-top: 20px;
}
table, th, td {
border: 2.5px solid black;
align-content: center;
}
table{
width: 80%;
text-align: center;
}
th{
height: 50px;
align-content: right;
background-color: orange;
}
th:hover {background-color: #3e8e41}
th,td{
width: 30%;
}
.button1 {
padding: 10px 15px;
font-size: 14px;
text-align: center;
cursor: pointer;
outline: none;
color: #fff;
background-color: orange;
border: none;
border-radius: 15px;
box-shadow: 0 9px #999;
}
.button1:hover {background-color: #3e8e41}
.button1:active {
background-color: #3e8e41;
box-shadow: 0 5px #666;
transform: translateY(4px);
}
<!DOCTYPE html>
<html>
<head>
<title>Api hit with JSON</title>
<link rel="stylesheet" type="text/css" href="css/bootstrap.min.css">
<link rel="stylesheet" type="text/css" href="css/style.css">
<script
src="https://code.jquery.com/jquery-3.3.1.js"
integrity="sha256-2Kok7MbOyxpgUVvAk/HJ2jigOSYS2auK4Pfzbm7uH60="
crossorigin="anonymous"></script>
<script type="text/javascript" src="js/jquery.min.js"></script>
<script type="text/javascript" src="js/script.js"></script>
</head>
<body>
<center><u class="h1">AJAX</u> api with JSON</center>
<center>
<div class="h2">
<label>Enter the parameter</label>
<input type="number" name="" id="para">
<button id="api">Submit</button>
</div>
<div id="h"></div>
<div id="data"></div>
</center>
</body>
</html>
This is my file, I hit the demo api with link and get the data to dynamic table but I want to restrict duplicate files in the dynamic table.
$(document).ready(function () {
//count = 1;
var counter=1,flag=0;
$("#api").click(function () {
var index = ($("#para").val());
if (index == "") {
alert("Please input data");
return false;
}
else{
$.ajax({
url: 'https://jsonplaceholder.typicode.com/todos/'+index,
type: 'GET',
dataType: 'json',
crossDomain: true,
success: function (data, textStatus, xhr) {
console.log(data);
var tr = [];
if(flag==0){
mytable = $('<table></table>').attr({ id: "basicTable", class:"basicTable1" });
//for (var i = 0; i < count; i++) {
let ab = $('<h1>API Data</h1>').appendTo("#h");
let row = $('<tr></tr>').appendTo(mytable);
let row1 = $('<tr id="row'+counter+'" ></tr>').appendTo(mytable);
$.each(data, function(key, val) {
$('<th></th>').text(key).appendTo(row);
$('<td></td>').text(val).appendTo(row1);
});
let row2 = $('<button class="button1" id="button'+ counter+'" onclick=removeFun('+ counter+')>remove Row</button>').appendTo(row1);
flag=1;
counter++;
//}
mytable.appendTo("#data");
}
else{
//for (var i = 0; i < count; i++) {
let row = $('<tr id="row'+counter+'" ></tr>').appendTo(mytable);
$.each(data, function(key, val) {
$('<td></td>').text(val).appendTo(row);
});
let row1 = $('<button class="button1" id="button'+ counter+'" onclick=removeFun('+ counter+')>remove Row</button>').appendTo(row);
counter++;
//}
mytable.appendTo("#data");
}
},
error: function (xhr, textStatus, errorThrown) {
console.log(errorThrown);
alert("No Record Found");
}
});
}
});
});
function removeFun(a){
$("#row"+a).remove();
}
first you need to remove duplicates from your "data"
var GroupByColumn = function (SourceData, columnName) {
var Unique = {};
var groupByColumn = columnName;
var tempData = SourceData;
for (var i = 0; i < tempData.length; i++) {
if (!Unique[tempData[i][groupByColumn]])
Unique[tempData[i][groupByColumn]] = [];
Unique[tempData[i][groupByColumn]].push(tempData[i]);
}
return Unique;
}
by using above function you can find a unique data
var z= [
{
"userId": 1,
"id": 1,
"title": "delectus aut autem",
"completed": false
},
{
"userId": 1,
"id": 2,
"title": "quis ut nam facilis et officia qui",
"completed": false
}
]
GroupByColumn(z,"id")
GroupByColumn(z,"title")
GroupByColumn(z,"completed")
GroupByColumn(z,"userId")
depepends on your need it will return your data. hope this will be helpful
I have 3 Files.
index.html
code.gs and
display.html
index.html
<!DOCTYPE html>
<html>
<head>
<style>
.my_text
{
font-family: Tahoma;
font-size: 13px;
font-weight: normal;
}
</style>
<base target="_top">
<script>
function displayMessage() {
var searchTerm;
searchTerm = document.getElementById('idSrchTerm').value;
console.log('searchTerm: ' + searchTerm );
google.script.run.withSuccessHandler(handleResults).processForm(searchTerm.replace("'","\'"));
}
function handleResults(results){
var length=results.length;
var table = document.getElementById("output");
var count = document.getElementById("count");
for(var i=0;i<length;i++)
{
var item=results[i];
item=item.split("|~|");
count.innerHTML = "Total Records Found : " + length;
table.innerHTML +="</br><a href='"+item[1]+"' target='_blank'>"+item[0]+"</a></br> <B>Owner: </B>" +item[3]+ " </br><B>Last modified: </B>"+item[2]+ " </br> <B>File Size: </B>"+item[4]+"</br>";
}
}
function clearBox(elementID)
{
document.getElementById("output").innerHTML = "";
document.getElementById("count").innerHTML = "";
}
</script>
<style>
table, th, td {
border: 1px solid black;
}
</style>
</head>
<body>
<div class="container">
<p class = "my_text"><input type="text" id="idSrchTerm" name="search" class = "my_text" >
<input type="button" value="Search Drive" name="submitButton" class = "my_text" onClick="clearBox(); displayMessage();" />
<?var url = getScriptUrl();?><a target="_blank" href='<?=url?>?page=display'><input type="button" value="Open In New Tab" name="submitButton" class = "my_text" onClick="clearBox(); displayMessage();" value='display.html'/></a>
</div>
<div id = "count" class = "my_text">
</div>
<div id ="output" class = "my_text">
</div>
</body>
</html>
code.gs
var scriptProperties = PropertiesService.getScriptProperties();
function doGet(e) {
Logger.log( Utilities.jsonStringify(e) );
if (!e.parameter.page) {
return HtmlService.createTemplateFromFile('index').evaluate();
}
return HtmlService.createTemplateFromFile(e.parameter['page']).evaluate();
return HtmlService.createHtmlOutputFromFile('display');
}
function getScriptUrl() {
var url = ScriptApp.getService().getUrl();
return url;
}
function SearchFiles(searchTerm) {
var searchFor ="fullText contains '" + searchTerm + "'"; //single quotes are needed around searchterm
var userProperties = PropertiesService.getUserProperties();
userProperties.setProperty('SQuery', searchTerm);
var userProperties = PropertiesService.getUserProperties();
var SQuery = userProperties.getProperty('SQuery');
Logger.log(SQuery);
var names = [];
var files = DriveApp.searchFiles(searchFor);
var searchQ = searchTerm;
while (files.hasNext()) {
var file = files.next();
var fileId = file.getId();// To get FileId of the file
var lm = file.getLastUpdated();
var OType = file.getOwner().getName();
var fsize = file.getSize()
var name = file.getName()+"|~|"+file.getUrl()+"|~|"+lm+"|~|"+OType+"|~|"+fsize+"|~|"+searchQ; // Im concatenating the filename with file id separated by |~|
names.push(name); // adding to the array
Logger.log(file.getUrl());
}
return names; // return results
}
// Process the form
function processForm(searchTerm) {
var resultToReturn;
Logger.log('processForm was called! ' + searchTerm);
resultToReturn = SearchFiles(searchTerm);
Logger.log('resultToReturn: ' + resultToReturn);
return resultToReturn; // return the results
}
display.html
<!DOCTYPE html>
<html>
<head>
<style>
.my_text
{
font-family: Tahoma;
font-size: 13px;
font-weight: normal;
}
</style>
<base target="_top">
<script>
function displayMessage() {
var searchTerm;
searchTerm = document.getElementById('idSrchTerm').value;
console.log('searchTerm: ' + searchTerm );
google.script.run.withSuccessHandler(handleResults).processForm(searchTerm.replace("'","\'"));
}
function handleResults(results){
var length=results.length;
var table = document.getElementById("output");
var count = document.getElementById("count");
for(var i=0;i<length;i++)
{
var item=results[i];
item=item.split("|~|");
count.innerHTML = "Total Records Found : " + length;
table.innerHTML +="</br><a href='"+item[1]+"' target='_blank'>"+item[0]+"</a></br> <B>Owner: </B>" +item[3]+ " </br><B>Last modified: </B>"+item[2]+ " </br> <B>File Size: </B>"+item[4]+"</br>";
}
}
function clearBox(elementID)
{
document.getElementById("output").innerHTML = "";
document.getElementById("count").innerHTML = "";
}
</script>
<style>
table, th, td {
border: 1px solid black;
}
</style>
</head>
<body onload ="clearBox(); displayMessage();">
<div class="container">
<p class = "my_text">
<input type="text" id="idSrchTerm" name="search" class = "my_text" value = "outing" >
</div>
<div id = "count" class = "my_text">
</div>
<div id ="output" class = "my_text">
</div>
</body>
</html>
actually the output of index.html and output.html are the same they have textbox and the other one has a button. This code is working my only proble here is how can I pass textbox value from index.html to textbox value of display.html
This is what index.html looks like
and this is what display.html looks like
my only target here is to pass textbox value from one site to another and from that I can run my code <body onload> Thats all i need pass textbox value from another textbox from other site TYSM for help
Ty local storage
save the variable
localStorage.setItem('NameOfLocalStorage',Value);
Get the value
localStorage.getItem('NameOfLocalStorage');
You can send data via link, example:
window.location.href = "output.html?" + encodeURIComponent('blah blah bla')
and you can retrive data in output.html
var data = decodeURIComponent(window.location.search.substr(1))
I'm having problem with javascript sort function. I have this function:
var compare = function(a, b) {
if(a.last_nom < b.last_nom) {
return -1;
}
if(a.last_nom > b.last_nom) {
return 1;
}
return 0;
}
And the I call it with:
var sortedData = fullData.sort(compare);
But I don't know how to pass dates correctly.
You can find jsbin example here
Thank you in advance
As requested, to make sense of my code here is full code:
<html lang="en-US">
<head>
<link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/materialize/0.97.0/css/materialize.min.css">
<link href="http://fonts.googleapis.com/icon?family=Material+Icons" rel="stylesheet">
<link href="https://cdnjs.cloudflare.com/ajax/libs/sweetalert/1.1.0/sweetalert.min.css" rel="stylesheet">
<link rel="icon" href="http://www.mzirafos.lt/favicon.ico" type="image/x-icon" />
<link rel="shortcut icon" href="http://www.mzirafos.lt/favicon.ico" type="image/x-icon" />
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0" />
<title>Mėmelio Žirafos - Facebook feeds page</title>
<style>
html {
overflow-y: scroll;
}
header {
margin-bottom: 50px;
}
.progress {
top: 50%;
width: 50%;
margin: 0 auto;
}
.event-only .not-event {
display: none;
}
.post-by {
display: block;
margin-bottom: 25px;
}
.post-date {
display: block;
}
.card .card-content .card-title {
line-height: 26px;
margin-bottom: 15px;
display: inline-block;
}
img.responsive-img {
width: 100%;
}
</style>
</head>
<body>
<div class="progress">
<div class="indeterminate"></div>
</div>
<div class="hide" id="content">
<!--header-->
<header>
<nav class="top-nav">
<div class="container">
<div class="nav-wrapper">
<p>Mėmelio Žirafos Facebook feeds page</p>
</div>
</div>
</nav>
</header>
<!--end header-->
<div class="container">
<div class="row">
<!--checkbox to show all posts or events only-->
<div class="col s6">
<p>
<input type="checkbox" id="events-only" />
<label for="events-only">Show events only</label>
</p>
</div>
<!--end checkbox-->
</div>
<div class="row">
<h3 class="center-align" id="posts-acc-title">Facebook posts</h3>
<!--posts wrapper-->
<div class="col s12" id="fb-posts-wrap"></div>
<!--end posts wrapper-->
</div>
</div>
</div>
<script src="https://code.jquery.com/jquery-2.1.4.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/materialize/0.97.0/js/materialize.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/sugar/1.4.1/sugar.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/sweetalert/1.1.0/sweetalert.min.js"></script>
<script src="https://cdn.rawgit.com/zenorocha/clipboard.js/master/dist/clipboard.min.js"></script>
<script>
(function() {
/*
* Our Globals
*/
var html = '';
var finalData = [];
var token = 'CAAQYWWjo5zkBAGlqs2AxxsWKcgWEI0VM3UA7555dhCQEOCTu9VW91tpfaNvrt4tS0w8DkxPJHvRENRrMeDT9QC1aSvHdZA7nhw9ZBqZAyUhMM6PTQoJggn7pJRHEO8xQJp8lsGZAqixVU8SvrMlhUUhwmzB11h9ISqd3MvmoD4aVZBPPD1geO';
var baseURL =
'https://graph.facebook.com/v2.4/{slug}/feed?fields=picture,created_time,message,link,type,description,caption,full_picture,id,admin_creator,from&limit=50&access_token={token}';
var slugs = [{
slug: 'sisaidgallery',
complete: false
}, {
slug: 'duzenos',
complete: false
}, {
slug: 'bbcnews',
complete: false
}, {
slug: 'Klaipeda.renginiai',
complete: false
}, {
slug: 'PORTbyBarBara',
complete: false
}, {
slug: 'Kastonas',
complete: false
}, {
slug: 'klaipedosdramosteatras',
complete: false
}, {
slug: '238899589464193',
complete: false
}];
/*
* allComplete
*/
var allComplete = function() {
for (var i = 0; i < slugs.length; i++) {
if (slugs[i].complete === false) {
return false;
}
}
return true;
};
/*
* makeURL
*/
var makeURL = function(url, token, slug) {
return url.replace('{token}', token).replace('{slug}', slug);
};
/*
* Date formatter
*/
var dateFormatter = function(date) {
var dateFormat = '{HH}:{mm}, {Weekday}, {d} {Month}, {yyyy}';
return Date.create(date).format(dateFormat);
}
/*
* Mark slug as complete
*/
var completeSlug = function(mySlug) {
for (var i in slugs) {
if (slugs[i].slug === mySlug) {
slugs[i].complete = true;
}
}
};
var copyTextID = 100;
/*
* template
*/
var template = '' +
'<div class="card blue-grey darken-1 hoverable {isEvent}">' +
'<div class="card-content white-text">' +
'<span class="post-date">Posted on: {fb-post-date}</span>' +
'<span class="post-by">Post by: {fb-post-from}</span>' +
'<div class="row">' +
'<div class="col s2">' +
'<img class="responsive-img" src="{fb-image}" alt=""/>' +
'</div>' +
'<div class="col s10" id="post-target-{fb-post-id}">' +
'<span class="card-title">{fb-post-title}</span>' +
'<p>{fb-post-text}</p>' +
'</div>' +
'</div>' +
'</div>' +
'<div class="card-action">' +
'<a target="_blank" href="{fb-post-link}">Open post</a>' +
'<a class="waves-effect waves-light btn white-text red darken-1 hoverable" data-clipboard-target="#post-target-{fb-post-id}"><i class="material-icons right">subject</i>Copy</a>' +
'</div>' +
'</div>';
/*
* checking title, text and images
*/
var replaceUndefined = function(str) {
return str === undefined ? '' : str;
};
var replaceImage = function(str) {
return str === undefined ? 'https://placehold.it/350x150' : str;
};
/*
* bindTemplate
*/
var bindTemplate = function(template, obj) {
return template
.replace('{isEvent}', obj.type === 'event' ? '' : 'not-event')
.replace('{fb-image}', replaceImage(obj.picture))
.replace('{fb-post-from}', obj.from.name)
.replace('{fb-post-title}', replaceUndefined(obj.description))
.replace('{fb-post-text}', replaceUndefined(obj.message))
.replace('{fb-post-link}', obj.link)
.replace('{fb-post-date}', dateFormatter(obj.created_time))
.replace(/{fb-post-id}/g, obj.id);
};
var makeAjax = function(fbUrl, next, slug) {
$.ajax({
url: fbUrl
}).done(function(data) {
next(data, slug);
});
};
/*
* renderTemplate
*/
var renderTemplate = function() {
$('#fb-posts-wrap').html(html);
};
/*
* makeAjaxCalls
*/
var makeAjaxCalls = function(slugs) {
slugs.forEach(function(slug) {
makeAjax(makeURL(baseURL, token, slug.slug), showAllPosts, slug.slug);
});
};
/*
* Flatten data
*/
var flattenData = function(data) {
var fullData = [];
var empty = [];
data.forEach(function(row) {
fullData.push(row.data);
});
return empty.concat.apply(empty, fullData);
};
var compare = function(a, b) {
if (a.last_nom < b.last_nom) {
return -1;
}
if (a.last_nom > b.last_nom) {
return 1;
}
return 0;
}
var showAllPosts = function(data, slug) {
// Let's first mark this slug as complete
completeSlug(slug);
// And store our data
finalData.push(data);
if (allComplete()) {
// merge all data
var fullData = flattenData(finalData);
// sort all data and
var sortedData = fullData.sort(compare);
// build the html
sortedData.forEach(function(obj) {
html += bindTemplate(template, obj);
});
// call the renderTemplateFunction
renderTemplate();
// finally hide the progress bar
$('.progress').fadeOut();
$('#content').removeClass('hide');
}
};
/*
* Listen to the change in the checkbox
*/
$('#events-only').change(function() {
if ($(this).is(':checked')) {
// hide the non events with css
$('#fb-posts-wrap').addClass('event-only');
} else {
// show the non events with css
$('#fb-posts-wrap').removeClass('event-only');
}
});
/*
* Kick off
*/
makeAjaxCalls(slugs);
})();
</script>
</body>
</html>
What is last_nom? There is no such function in JS Date specification
Try this:
function compare(a, b) {
if (a.getTime() > b.getTime())
return 1;
if (a.getTime() < b.getTime())
return -1;
return 0
}
var sortedDatesArray = unsortedDatesArray.sort(compare);