An array can't be used in datatables - javascript

I have tried to make a table by using datatables with an array, but somehow it doesn't show the table on my html file.
The array is defined in my gs file as you can see in the code below.
It's a simple work but I'm still not sure what it went wrong.
var ssId = 'xxxxxxxxxxxxx';
var ss = SpreadsheetApp.openById(ssId);
var indexPage_sheetName = 'xxxxxxxx';
var valuesFromIndexPage = ss.getSheetByName(indexPage_sheetName).getDataRange().getValues();//array of 850rows×15cols
valuesFromIndexPage.shift();
function getData() {
$(document).ready(function(){
$("#foo-table").DataTable({
data: valuesFromIndexPage
});
});
}
<html>
<head>
<script src="//ajax.aspnetcdn.com/ajax/jquery/jquery-1.9.1.js"></script>
<link rel="stylesheet" href="https://cdn.datatables.net/1.10.20/css/jquery.dataTables.min.css"/>
<script src="https://cdn.datatables.net/1.10.20/js/jquery.dataTables.min.js"></script>
<body>
<table id="foo-table" class="display" width="100%"></table>
</body>
</head>
</html>
#ZektorH Here's the console log of running my code.
userCodeAppPanel:9 Uncaught TypeError: Cannot read property 'slice' of null
at initializeTable (userCodeAppPanel:9)
at af (4105580746-mae_html_user_bin_i18n_mae_html_user__ja.js:67)
at 4105580746-mae_html_user_bin_i18n_mae_html_user__ja.js:10
at ng.J (4105580746-mae_html_user_bin_i18n_mae_html_user__ja.js:94)
at Hd (4105580746-mae_html_user_bin_i18n_mae_html_user__ja.js:42)
at Dd (4105580746-mae_html_user_bin_i18n_mae_html_user__ja.js:43)
at Bd.b (4105580746-mae_html_user_bin_i18n_mae_html_user__ja.js:39)
I looked again at my data and I found out the data became null on console.log(but it has data when I see it on Logger.log).
I'm posting what I did and got below.
function getData() {
Logger.log(valuesFromIndexPage); //the array is in valuesFromIndexPage
return valuesFromIndexPage;
}
function initializeTable(data) {
console.log(data); //it returns null here...
var aDataSet = data.slice(1);
The log from Logger.log
[19-10-31 09:47:00:116 JST] [[ID, 案件名, .......
#ZektorH These're the whole codes without data.
code.gs
var ssId = 'xxxxxxxxxxxxxxxxxxxxxxxxx';
var ss = SpreadsheetApp.openById(ssId);
var indexPage_sheetName = 'xxxxxxxxxxxxxx';
var valuesFromIndexPage = ss.getSheetByName(indexPage_sheetName).getDataRange().getValues();
function createSidebar() {
SpreadsheetApp.getUi().showSidebar(HtmlService.createHtmlOutputFromFile('index').setTitle('My custom sidebar').setWidth(300))
}
function getData() {
return valuesFromIndexPage;
}
function doGet(e) {
return HtmlService.createTemplateFromFile('index').evaluate().setTitle('title');
}
index.html
<!DOCTYPE html>
<html>
<head>
<base target="_top">
<script src="https://code.jquery.com/jquery-3.4.1.min.js" integrity="sha256-CSXorXvZcTkaix6Yvo6HppcZGetbYMGWSFlBw8HfCJo=" crossorigin="anonymous"></script>
<link rel="stylesheet" type="text/css" href="https://cdn.datatables.net/1.10.20/css/jquery.dataTables.css">
<script type="text/javascript" charset="utf8" src="https://cdn.datatables.net/1.10.20/js/jquery.dataTables.js"></script>
<script>
$(document).ready(function() {
console.log("ready!");
google.script.run.withSuccessHandler(initializeTable).getData(); //calls the getData funciton from Apps Script and returns the results to the initializeTable function
});
function initializeTable(data) {
console.log(data)
var aDataSet = data.slice(1); // all except header
var head = []; // headers
data[0].forEach(function(e) {
head.push({
'sTitle': e
});
});
$('#foo-table').dataTable({
"aaData": aDataSet,
"aoColumns": head
});
}
</script>
</head>
<body>
<table id="foo-table" class="display" width="100%"></table>
</body>
</html>

Chage with columns of of key in dataTable for table headers and chage $("#foo-table").DataTable at $("#foo-table").dataTable
var valuesFromIndexPage=[{"free-text-c1":"free-text-r1","c2":"r1","c3":"r1","c4":"r1","c5":"r1","c6":"r1","c7":"r1","c8":"r1","c9":"free-text-r1","c10":"free-text-r1"},{"free-text-c1":"free-text-r2","c2":"r2","c3":"r2","c4":"r2","c5":"r2","c6":"r2","c7":"r2","c8":"r2","c9":"free-text-r2","c10":"free-text-r2"}];
valuesFromIndexPage.shift();
function getData() {
$(document).ready(function(){
$("#foo-table").dataTable({
destroy: true,
scrollX: true,
data: valuesFromIndexPage,
columns: _.keys(valuesFromIndexPage[0]).map((key) => { return { "title": key, "data": key } })
});
});
}
getData()
<script src="https://cdnjs.cloudflare.com/ajax/libs/lodash.js/4.17.15/lodash.js"></script>
<html>
<head>
<script src="//ajax.aspnetcdn.com/ajax/jquery/jquery-1.9.1.js"></script>
<link rel="stylesheet" href="https://cdn.datatables.net/1.10.20/css/jquery.dataTables.min.css"/>
<script src="https://cdn.datatables.net/1.10.20/js/jquery.dataTables.min.js"></script>
<body>
<table id="foo-table" class="display" width="100%"></table>
</body>
</head>
</html>

Assuming you are using it on a sidebar, I was able to get it to work like this:
Apps Script
function createSidebar() {
SpreadsheetApp.getUi().showSidebar(HtmlService.createHtmlOutputFromFile('sidebar').setTitle('My custom sidebar').setWidth(300))
}
function getData() {
return SpreadsheetApp.getActiveSheet().getDataRange().getValues();
}
HTML Page
<!DOCTYPE html>
<html>
<head>
<base target="_top">
<script src="https://code.jquery.com/jquery-3.4.1.min.js" integrity="sha256-CSXorXvZcTkaix6Yvo6HppcZGetbYMGWSFlBw8HfCJo=" crossorigin="anonymous"></script>
<link rel="stylesheet" type="text/css" href="https://cdn.datatables.net/1.10.20/css/jquery.dataTables.css">
<script type="text/javascript" charset="utf8" src="https://cdn.datatables.net/1.10.20/js/jquery.dataTables.js"></script>
<script>
$(document).ready(function() {
console.log("ready!");
google.script.run.withSuccessHandler(initializeTable).getData(); //calls the getData funciton from Apps Script and returns the results to the initializeTable function
});
function initializeTable(data) {
var aDataSet = data.slice(1); // all except header
var head = []; // headers
data[0].forEach(function(e) {
head.push({
'sTitle': e
});
});
$('#foo-table').dataTable({
"aaData": aDataSet,
"aoColumns": head
});
}
</script>
</head>
<body>
<table id="foo-table" class="display" width="100%"></table>
</body>
</html>
Hope this helps!

Related

Creating an autocomplete function in Google script that works with a list of values from the Google Sheet

I'm trying to create an autocomplete text field, that autocompletes the country that's filled in, if the country already exists in the google sheet. At the moment my code only works, when I write all the possible countries in the 'availabletags' variable. But I want it to get the values directly from the google sheet. This is the html & script:
<html>
<head>
<meta charset="utf-8">
<meta name="viewport" content="width=device-width, initial-scale=1">
<link rel="stylesheet" href="//code.jquery.com/ui/1.12.1/themes/base/jquery-ui.css">
<link rel="stylesheet" href="/resources/demos/style.css">
<script src="https://code.jquery.com/jquery-1.12.4.js"></script>
<script src="https://code.jquery.com/ui/1.12.1/jquery-ui.js"></script>
</head>
<body>
<div class="ui-widget">
<label for="text">country</label>
<input id="text">
</div>
<div>
<button id="btn"> Run it! </button>
</div>
<script>
$(function() {
var availableTags = [ //should be changed to availableTags = list;
"belgium",
"france",
"greece",
"spain",
"italy",
"the netherlands"
];
$("#text").autocomplete({
source: availableTags
});
});
document.getElementById("btn").addEventListener("click", doStuff);
function doStuff() {
var ucountry = document.getElementById("text").value;
google.script.run.userClicked(ucountry);
document.getElementById("text").value = "";
};
</script>
</body>
</html>
I wrote following code in google script to retrieve the countries from the google script, and when I look at the log, the list of countries from the google sheet is indeed in the list variable.
function doGet() {
var ws = SpreadsheetApp.getActiveSpreadsheet().getSheetByName("Data");
var list = ws.getRange(1,1,ws.getRange("A1").getDataRegion().getLastRow(),1).getValues(); // contains countries
Logger.log(list);
var template = HtmlService.createTemplateFromFile("page");
template.list = list.map(function(r){return r[0]; });
var html = template.evaluate();
return html;
}
function userClicked(country){
var url = "https://docs.google.com/spreadsheets/d/1IMxZwN3swMTf9EoF_k3iRV7Zc6iwzoWzov5-qC_MSKU/edit#gid=0";
var ss = SpreadsheetApp.openByUrl(url);
var ws = ss.getSheetByName("Data");
ws.appendRow([country]);
}
I would like to have the var availableTags = list; But when I do that, the autocomplete stops working. Any help would be appreciated!
Use google.script.run with SuccessHandler
This implies the creation of an additional .gs function that will be called from clientside onload.
Sample:
Code.gs
function doGet() {
var template = HtmlService.createTemplateFromFile("page");
var html = template.evaluate();
return html;
}
function getCountry(){
var ws = SpreadsheetApp.getActiveSpreadsheet().getSheetByName("Data");
var list = ws.getRange(1,1,ws.getRange("A1").getDataRegion().getLastRow(),1).getValues(); // contains countries
list = list.map(function(r){return r[0]; });
Logger.log(list);
return list;
}
function userClicked(country){
var url = "https://docs.google.com/spreadsheets/d/1IMxZwN3swMTf9EoF_k3iRV7Zc6iwzoWzov5-qC_MSKU/edit#gid=0";
var ss = SpreadsheetApp.openByUrl(url);
var ws = ss.getSheetByName("Data");
ws.appendRow([country]);
}
page.html
<html>
<head>
<meta charset="utf-8">
<meta name="viewport" content="width=device-width, initial-scale=1">
<link rel="stylesheet" href="//code.jquery.com/ui/1.12.1/themes/base/jquery-ui.css">
<link rel="stylesheet" href="/resources/demos/style.css">
<script src="https://code.jquery.com/jquery-1.12.4.js"></script>
<script src="https://code.jquery.com/ui/1.12.1/jquery-ui.js"></script>
</head>
<body>
<div class="ui-widget">
<label for="text">country</label>
<input id="text">
</div>
<div>
<button id="btn"> Run it! </button>
</div>
<script>
google.script.run.withSuccessHandler(tags).getCountry();
function tags(list) {
console.log(list);
var availableTags = list;
$("#text").autocomplete({
source: availableTags
});
};
document.getElementById("btn").addEventListener("click", doStuff);
function doStuff() {
var ucountry = document.getElementById("text").value;
google.script.run.userClicked(ucountry);
document.getElementById("text").value = "";
};
</script>
</body>
</html>

JavaScript functions are not interpreted when using PivotTable.js

I have integrated PivotTable.js on my web application. The pivot table is shown normally but in some first columns and rows, functions are written and it is not interpreted (See the screenshot) This is an example of a function written:
function each(iterator, context) {
var index = 0;
try {
this._each(function(value) {
iterator.call(context, value, index++);
});
} catch (e) {
if (e != $break) throw e;
}
return this;
}
These are screenshots taken from the result:
pivot_table
Pivot table2
This is my code:
<script type="text/javascript" src="./jquery-1.11.0.min.js"></script>
<script type="text/javascript" src="./jquery-ui.min.js"></script>
<script type="text/javascript" src="./jquery.ui.touch-punch.min.js"></script>
<script type="text/javascript" src="./pivot.min.js"></script>
<script type="text/javascript" src="./tips_data.min.js"></script>
<link rel="stylesheet" href="./pivot.min.css">
<script type="text/javascript">
jQuery.noConflict();
jQuery(document).ready(function($) {
$("#output").pivotUI(
$.pivotUtilities.tipsData, {
rows: ["sex", "smoker"],
cols: ["day", "time"],
vals: ["tip", "total_bill"],
aggregatorName: "Sum over Sum",
rendererName: "Heatmap"
});
});
</script>
<div id="output"></div>
THe issue is referenced officially here: https://github.com/nicolaskruchten/pivottable/issues/708
As i understand, no out-of-the-box solution yet.

Uncaught ReferenceError: isApp is not defined

I am getting "Uncaught ReferenceError: isApp is not defined" in the console,
I had tried to find solution for this error from long morning but didn't able to get much, both of my isApp.js and mApp.js are saved in folder named as "js", can someone please help me to get out of this thing....thanks in advance
//"......isApp.js file code starts from here..............."
var iA = function () {
var t = this;
this.user;
var IsInvite = false;
this.serverUrl = someLocalhostUrl;
//some function - structure of functions is shown below
//this.function1 = function(){
//do something
//};
//lot of function
this.initialize = function () {
t.getUser();
var pk = typeof t.user;
if (!(typeof t.user === 'object')) {
t.user = null;
t.setUser();
}
}();
};
var isApp = new iA();
//"......isApp.js file code endss here..............."
//"......mApp.js file code starts from here..............."
var mApp = function () {
//var PostUrl = "http://localhost:52015/"
var PostUrl = isApp.serverUrl + "/";
var t = this;
var u = {};
this.ph, this.loc;
var user, Email, UserName;
var LoggedIn;
this.initiate = function () {
u = isApp.getUser();
if (u && u.LoggedIn) {
if (window.location.href.indexOf("index") == -1)
$.mobile.changePage("index.html#p-start");
//window.location = "index.html#p-home";
}
};
//some function - structure of functions is shown below
//this.function1 = function(){
//do something
//};
//lot of function
this.initiate();
};
m = new mApp();
//"......mApp.js file code ends here..............."
<!DOCTYPE html>
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
<title></title>
<style>
</style>
<meta charset="utf-8" />
<meta name="viewport" content="width=device-width, initial-scale=1">
<!--css starts here-->
<link href="css/jquery.mobile-1.4.5.css" rel="stylesheet" />
<link href="css/custom.css" rel="stylesheet" />
<!--css ends here-->
<!--js starts here-->
<script src="js/jquery.js"></script>
<script src="js/jquery.mobile-1.4.5.js"></script>
<script src="js/jquery.signalR-2.2.0.min.js"></script>
<script src="js/mApp.js"></script>
<script src="js/isApp.js"></script>
<script src="js/home.js"></script>
<!--js ends here-->
<!--<script>
$(function () {
$('.image').click(function () {
alert("selection needed");
});
document.getElementById("startDate").valueAsDate = new Date();
});
</script>-->
</head>
<body>
<div data-role="page" id="p-start">
<div data-role="main" class="ui-content ui-responsive ui-body-a">
<div class="align-center">
<h3>Its our Rocking app</h3>
<a href="#p-login">
<img src="images/temp-logo.jpg" class="logo" />
</a>
</div>
</div>
</div>
</body>
</html>
You load your mApp.js file before your isApp.js file and both scripts are executed right away, so naturally the function isn't defined yet when mApp.js is executed.
<script src="js/mApp.js"></script>
<script src="js/isApp.js"></script>

JS not giving any result(Objects)

Please have a look at the following code:
HTML:
<!DOCTYPE html>
<html>
<head>
<title>Using Javascript</title>
<meta http-equiv="author" content="infinite_999">
<link rel="stylesheet" type="text/css" href="css.css">
</head>
<body>
<div id="name"></div>
<div id="rooms"></div>
<div id="booked"></div>
<div id="available"></div>
<script src="javascript.js"></script>
</body>
</html>
Javascript:
var hotel={
//Properties
name:'Pacific Idea',
rooms:20,
booked:15,
//Methods
checkAvailability = function () {
return this.rooms- this.booked;
}
};
var nameHotel=document.getElementById('name');
var roomHotel=document.getElementById('rooms');
var bookedHotel=document.getElementById('booked');
var availableHotel=document.getElementById('available');
nameHotel.textContent=hotel.name;
roomsHotel.textContent=hotel.rooms;
bookedHotel.textContent=hotel.booked;
availableHotel.textContent=hotel.checkAvailability();
Now according to this code, the name, number of booked rooms, number of available rooms of the hotel should be displayed. But unfortunately, it just doesn't display anything.
Please help me..
2 errors in your javascript code. one is checkAvailability = function (); should be ':' instead of '='. and roomsHotel typo error.
Try
var hotel={
//Properties
name:'Pacific Idea',
rooms:20,
booked:15,
//Methods
checkAvailability : function () {
return this.rooms- this.booked;
}
};
var nameHotel=document.getElementById('name');
var roomsHotel=document.getElementById('rooms');
var bookedHotel=document.getElementById('booked');
var availableHotel=document.getElementById('available');
nameHotel.textContent=hotel.name;
roomsHotel.textContent=hotel.rooms;
bookedHotel.textContent=hotel.booked;
availableHotel.textContent=hotel.checkAvailability();

Import Excel file to a table of HTML page

I have a simple Excel file in my computer at "D:/Book1.xls". I want to import it to make a table and append the table to a div tag in my HTML page.
Would you modify my code below?
<!DOCTYPE html>
<html>
<head>
<meta charset="EUC-KR">
<title>Insert title here</title>
<style type="text/css">
</style>
<script src='http://alasql.org/console/alasql.min.js'></script>
<script src='http://alasql.org/console/xlsx.core.min.js'></script>
<script src="./libs/jquery-2.1.4.js"></script>
<script type="text/javascript">
$(document).ready(function() {
alasql('select * into html("#res",{headers:true}) \
from xlsx("d:/Book1.xls",\
{headers:true})');
alert("end of function")
});
</script>
</head>
<body>
<div id="res">res</div>
</body>
</html>
The problem is you are trying to get access of file directly from web page which is not possible. You cannot access any file outside of you browser. For that you have to select the input element of html and after getting the file data you can store it to javascript variable.
<script src="alasql.min.js"></script>
<script src="xlsx.core.min.js"></script>
<p>Select CSV file to read:</p>
<input id="readfile" type="file" onchange="loadFile(event)"/>
<script>
function loadFile(event) {
alasql('SELECT * FROM FILE(?,{headers:true})',[event],function(data){
console.log(data);
// You can data to div also.
});
}
</script>
Scripts
<script src="http://ajax.aspnetcdn.com/ajax/modernizr/modernizr-2.8.3.js"></script>
<script src="http://code.jquery.com/jquery-1.11.3.min.js"></script>
<script src="http://code.jquery.com/ui/1.11.1/jquery-ui.min.js"></script>
<script type="text/javascript" src="http://cdn-na.infragistics.com/igniteui/2018.2/latest/js/infragistics.core.js"></script>
<script type="text/javascript" src="http://cdn-na.infragistics.com/igniteui/2018.2/latest/js/infragistics.lob.js"></script>
<script type="text/javascript" src="http://cdn-na.infragistics.com/igniteui/2018.2/latest/js/modules/infragistics.ext_core.js"></script>
<script type="text/javascript" src="http://cdn-na.infragistics.com/igniteui/2018.2/latest/js/modules/infragistics.ext_collections.js"></script>
<script type="text/javascript" src="http://cdn-na.infragistics.com/igniteui/2018.2/latest/js/modules/infragistics.ext_text.js"></script>
<script type="text/javascript" src="http://cdn-na.infragistics.com/igniteui/2018.2/latest/js/modules/infragistics.ext_io.js"></script>
<script type="text/javascript" src="http://cdn-na.infragistics.com/igniteui/2018.2/latest/js/modules/infragistics.ext_ui.js"></script>
<script type="text/javascript" src="http://cdn-na.infragistics.com/igniteui/2018.2/latest/js/modules/infragistics.documents.core_core.js"></script>
<script type="text/javascript" src="http://cdn-na.infragistics.com/igniteui/2018.2/latest/js/modules/infragistics.ext_collectionsextended.js"></script>
<script type="text/javascript" src="http://cdn-na.infragistics.com/igniteui/2018.2/latest/js/modules/infragistics.excel_core.js"></script>
<script type="text/javascript" src="http://cdn-na.infragistics.com/igniteui/2018.2/latest/js/modules/infragistics.ext_threading.js"></script>
<script type="text/javascript" src="http://cdn-na.infragistics.com/igniteui/2018.2/latest/js/modules/infragistics.ext_web.js"></script>
<script type="text/javascript" src="http://cdn-na.infragistics.com/igniteui/2018.2/latest/js/modules/infragistics.xml.js"></script>
<script type="text/javascript" src="http://cdn-na.infragistics.com/igniteui/2018.2/latest/js/modules/infragistics.documents.core_openxml.js"></script>
<script type="text/javascript" src="http://cdn-na.infragistics.com/igniteui/2018.2/latest/js/modules/infragistics.excel_serialization_openxml.js"></script>
JS
$(function () {
$("#input").on("change", function () {
var excelFile,
fileReader = new FileReader();
$("#result").hide();
fileReader.onload = function (e) {
var buffer = new Uint8Array(fileReader.result);
$.ig.excel.Workbook.load(buffer, function (workbook) {
var column, row, newRow, cellValue, columnIndex, i,
worksheet = workbook.worksheets(0),
columnsNumber = 0,
gridColumns = [],
data = [],
worksheetRowsCount;
// Both the columns and rows in the worksheet are lazily created and because of this most of the time worksheet.columns().count() will return 0
// So to get the number of columns we read the values in the first row and count. When value is null we stop counting columns:
while (worksheet.rows(0).getCellValue(columnsNumber)) {
columnsNumber++;
}
// Iterating through cells in first row and use the cell text as key and header text for the grid columns
for (columnIndex = 0; columnIndex < columnsNumber; columnIndex++) {
column = worksheet.rows(0).getCellText(columnIndex);
gridColumns.push({ headerText: column, key: column });
}
// We start iterating from 1, because we already read the first row to build the gridColumns array above
// We use each cell value and add it to json array, which will be used as dataSource for the grid
for (i = 1, worksheetRowsCount = worksheet.rows().count(); i < worksheetRowsCount; i++) {
newRow = {};
row = worksheet.rows(i);
for (columnIndex = 0; columnIndex < columnsNumber; columnIndex++) {
cellValue = row.getCellText(columnIndex);
newRow[gridColumns[columnIndex].key] = cellValue;
}
data.push(newRow);
}
// we can also skip passing the gridColumns use autoGenerateColumns = true, or modify the gridColumns array
createGrid(data, gridColumns);
}, function (error) {
$("#result").text("The excel file is corrupted.");
$("#result").show(1000);
});
}
if (this.files.length > 0) {
excelFile = this.files[0];
if (excelFile.type === "application/vnd.ms-excel" || excelFile.type === "application/vnd.openxmlformats-officedocument.spreadsheetml.sheet" || (excelFile.type === "" && (excelFile.name.endsWith("xls") || excelFile.name.endsWith("xlsx")))) {
fileReader.readAsArrayBuffer(excelFile);
} else {
$("#result").text("The format of the file you have selected is not supported. Please select a valid Excel file ('.xls, *.xlsx').");
$("#result").show(1000);
}
}
})
});
function createGrid(data, gridColumns) {
if ($("#grid1").data("igGrid") !== undefined) {
$("#grid1").igGrid("destroy");
}
$("#grid1").igGrid({
columns: gridColumns,
autoGenerateColumns: true,
dataSource: data,
width: "100%",
});
}
HTML
<input type="file" id="input" accept="application/vnd.ms-excel, application/vnd.openxmlformats-officedocument.spreadsheetml.sheet" />
<div id="result"></div>
<table id="grid1"></table>

Categories