Populating html sidebar with js variable data - google-apps-script

I'm a fast learning beginner with Google Sheets Script. In the apps I've done so far the sidebars I've made have included buttons and text, but nothing passed from variables. I'll note that I understand Javascript reasonably well, but haven't branched into jquery as yet, though I have a good book on the topic.
In this case I have variable values taken from two different spreadsheets that I'd like passed to the sidebar so that the user can view data and set an appointment.
My .gs code:(This is server side code)
function apptSidebar2() {
var html = HtmlService.createHtmlOutputFromFile('setApptsPage2')
.setTitle('Counselor Connect Easy!')
.setWidth(300);
SpreadsheetApp.getUi().showSidebar(html);
}
function setAppts2() {
//get all the data for client appointment
var setupSheet = SpreadsheetApp.getActiveSpreadsheet().getSheetByName('Setup');
var shID=setupSheet.getRange(1,2).getValue();
var feedSheet = SpreadsheetApp.openById(shID);
var dataSheet = feedSheet.getSheetByName('StudentData');
var lastColumn = dataSheet.getLastColumn();
var lastRow = dataSheet.getLastRow();
for(var i=lastRow;i>0;i--) {
if(dataSheet.getRange(i,1).getValue()==thisID) {
var clientData = dataSheet.getRange(i,1,1,lastColumn).getValues();
}
}
var SID = thisID;
var SLN = clientData[0][1];
var SFN = clientData[0][2];
var b1r = clientData[0][3].toString();
var b1t = clientData[0][4].toString();
var b1c = clientData[0][5].toString();
var SB1 = b1r+" "+b1t+" "+b1c;
var b2r = clientData[0][6].toString();
var b2t = clientData[0][7].toString();
var b2c = clientData[0][8].toString();
var SB2 = b2r+" "+b2t+" "+b2c;
var b3r = clientData[0][9].toString();
var b3t = clientData[0][10].toString();
var b3c = clientData[0][11].toString();
var SB3 = b3r+" "+b3t+" "+b3c;
var b4r = clientData[0][12].toString();
var b4t = clientData[0][13].toString();
var b4c = clientData[0][14].toString();
var SB4 = b4r+" "+b4t+" "+b4c;
var b5r = clientData[0][15].toString();
var b5t = clientData[0][16].toString();
var b5c = clientData[0][17].toString();
var SB5 = b5r+" "+b5t+" "+b5c;
var b6r = clientData[0][18].toString();
var b6t = clientData[0][19].toString();
var b6c = clientData[0][20].toString();
var SB6 = b6r+" "+b6t+" "+b6c;
apptSidebar2();
}
And my html for the sidebar, which I suspect is grossly uninformed in terms of how I need to connect the two. For all I know I'm closer than I think:
<!DOCTYPE html>
<html>
<link rel="stylesheet" href="https://ssl.gstatic.com/docs/script/css/add-ons1.css">
<head>
<base target="_top">
<link rel="stylesheet" href="//cdnjs.cloudflare.com/ajax/libs/timepicker/1.3.5/jquery.timepicker.min.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>
<script>
$( function() {
$( "#datepicker" ).datepicker();
} );
</script>
<script type="text/javascript">
function getStudent() {
if(!document.getElementById) return;
var apptDiv2 = document.getElementById("appt2");
}
</script>
</head>
<body>
<div id="container" style="padding: 10px; text-align:center;">
<div id="appt2">
<b>Student Data</b>
<p id="name">Student Name</p>
<p id = "id">nnnnn</p>
<p id = "reason">Why</p>
<p id = "notes">More why</p>
<p id = "blk1">Block 1</p>
<p id = "blk2">Block 2</p>
<p id = "blk3">Block 3</p>
<p id = "blk4">Block 4</p>
<p id = "blk5">Block 5</p>
<p id = "blk6">Block 6</p>
<input type="text" id="datepicker" value="click to choose date">
</div>
</div>
<div style=
"width: 100%;
position: fixed;
bottom: 0;
width: 100%;
text-align:center;
background-color:black;
text-color:white;">
<p><b>©FastAdmin Solutions</b></p>
</div>
</div>
</body>
</html>

Not meant to be a comprehensive answer:
You could change this:
<script>
$( function() {
$( "#datepicker" ).datepicker();
} );
</script>
To something like this
HTML(clientside):
<script>
$( function() {
$( "#datepicker" ).datepicker();
google.script.run
.withSuccessHandler('insertHtmlIntoADiv')
.getDesiredDataInHtmlFormat();
} );
function insertHtmlIntoADiv(hl){
$('#mydiv').html(hl);
}
</script>
CODE(ServerSide):
getDesiredDataInHtmlFormat(){
//generate html integrated with wanted data and store it in a string and return it. It will be picked up by the success handler.
}
For more info on google.script.run look here.

To directly set variables in the as-constructed sidebar, you'll need to create an HtmlTemplate from the sidebar's HTML file, pass that to the setAppts function, set those values on the template object, and then return the "filled" template to the calling function, to be built into an HtmlOutput and displayed:
function getApptSidebarOutput() {
var template = HtmlService.createTemplateFromFile("a filename");
fillAppts_(template);
return template.evaluate();
}
function fillAppts_(theTemplate) {
theTemplate.someVarName = some value;
theTemplate.otherVar = some other value;
...
return theTemplate;
}
In your HTML file, these variables can be used directly as someVarName and otherVar.
Recommended reading:
template guide
Adding variables to templates
Note that depending on what this data is and who is using it, you may be better off with a fully async design, where the sidebar is constructed without this data, and queries for up-to-date info periodically (like right before submitting an appointment request, or otherwise every 5-10 minutes). The idea being, schedule availabilities change, but the sidebar can be left open.

Related

how to transfer textbox value from app inventor to google sheet web app

i have created a google web app,
when i am typing a number in the orders textbox,
i'm getting a match result in the disabled amount textbox,
from the google sheet column,
the web app working good
now,what i want to do is to be able to create a textbox in app inventor
and when put an orders value and clicking a button
i will get the amount result on a label on the app invenotr interface
its not working on app inventor
here is the code i made in app inventor
[![enter image description here][1]][1]
this the Code.gs
function doGet(e) {
return HtmlService.createHtmlOutputFromFile('page');
}
function getCost(oneCode){
var url = "https://script.google.com/macros/s/AKfycbyX";
va
return "not found";
}
<!DOCTYPE html>
<html>
<head>
<base target="_top">
</head>
<script>
document.addEventListener("DOMContentLoaded", function() {
document.getElementById("one").addEventListener("change", doThis);
});
function doThis() {
var oneCode = document.getElementById("one").value;
google.script.run.withSuccessHandler(updateAmount).getCost(oneCode);
}
function updateAmount(cost) {
document.getElementById("two").value = cost;
}
</script>
<body>
<div>
<input id="one" type="text">
<label for="one">orders</label>
</div>
<div>
<input disabled id="two" type="text">
<label for="two">amount</label>
</div>
</body>
</html>
Try this:
function doThis() {
var oneCode = document.getElementById("one").value;
console.log(oneCode);
google.script.run.withSuccessHandler(updateAmount).getCost(oneCode);
}
and this:
function getCost(oneCode){
console.log('onecode');
var url = "https://script.google.com/macros/s/AKfycbyXX6axO9G9ANDW0LaQVgezT6hSzSld8CRt2VbsZV6v8XXwNus/exec";
var ss = SpreadsheetApp.openByUrl(url);
var ws = ss.getSheetByName("Sheet1");
var data = ws.getRange(1,1,ws.getLastRow(),2).getValues();
var ordersList = data.map(function(r){ return r[0].toString(); });
var amountList = data.map(function(r){ return r[1].toString(); });
var position = ordersList.indexOf(oneCode);
if(position > -1){
return amountList[position];
}
return "not found";
}
And then run the code and goto View/Executions and see where you losing the data.

returning data in app script from an HTML input

I am trying to lauch an html form from a google spread sheet using the HTMLService and return data to the script from a select input. I am collecting the data with this line:
-
But I am not sure how to get it back to the script file: I have tried various iterations of:
- city= form.Projects_list.text;
- city= form.Projects_list[0];
- city= form.Projects_list.[0][0];
but none of these seem to be the right handle to the select. The other variables are coming back from the form as desired.
How can I grab that last variable?
HTML File
<b>Add Row To Spreadsheet</b><br />
<form>
<meta charset="utf-8">
<meta name="viewport" content="width=device-width, initial-scale=1">
<title>jQuery UI Datepicker - Default functionality</title>
<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>
<script>
$( function() {
$( "#datepicker" ).datepicker();
} );
$( function() {
$( ".widget input[type=submit]" ).button();
$( "button, input, a" ).click( function( event ) {
event.preventDefault();
} );
} );
</script>
<form id = "dateform">
<p>Date: <input type="text" id="datepicker" name ="datepicker"></p><p></p>
Reason for Delay: <input id="reason" name="reason" type="text" />
Last name: <input id="lastName" name="lastName" type="text" />
<input onclick="formSubmit()" type="button" value="Add Row" />
<input onclick="google.script.host.close()" type="button" value="Exit" />
<hr>
<div id = 'pList'>
<table>
<tr>
<td>Select A City</td><td><select id="Projects_list"name ="Projects_list"></select></td>
</tr>
</table>
</div>
</form>
<script type="text/javascript">
function formSubmit() {
google.script.run.getValuesFromForm(document.forms[0]);
google.script.host.close();
}
</script>
<script type="text/javascript">
// Client-side JavaScript that uses the list returned by
// GAS function "getValuesForRngName()" to populate the dropdown.
// This is standard client-side JavaScript programming that uses
// DOM manipulation to get page elements and manipulate them.
function onSuccess(values) {
var opt,
dropDown;
for(i = 0;i < values.length; i +=1){
dropDown = document.getElementById("Projects_list");
opt = document.createElement("option");
dropDown.options.add(opt);
// Remember that GAS Range method "GetValues()" returns
// an array of arrays, hence two array indexes "[i][0]" here.
opt.text = values[i][0];
opt.value = values[i][0];
}
}
function populate(){
google.script.run.withSuccessHandler(onSuccess).getValuesForRngName('Projects20');
}
</script>
<script>
// Using the "load" event to execute the function "populate"
window.addEventListener('load', populate);
</script>
<script>
// Client-side JavaScript that uses the list returned by
// GAS function "getValuesForRngName()" to populate the dropdown.
// This is standard client-side JavaScript programming that uses
// DOM manipulation to get page elements and manipulate them.
function onSuccessx(values) {
var opt,
dropDown;
for(i = 0;i < values.length; i +=1){
dropDown = document.getElementById("Projects_list");
opt = document.createElement("option");
dropDown.options.add(opt);
// Remember that GAS Range method "GetValues()" returns
// an array of arrays, hence two array indexes "[i][0]" here.
opt.text = values[i][0];
opt.value = values[i][0];
}
dropDown = dropDown.options.sort()
}
function populatex(){
google.script.run.withSuccessHandler(onSuccess).getValuesForRngName('Projects20');
}
</script>
<script>
// Using the "load" event to execute the function "populate"
window.addEventListener('loadx', populate);
</script>
App Script File
function demoHtmlServices() {
var ss = SpreadsheetApp.getActiveSpreadsheet(),
html = HtmlService.createHtmlOutputFromFile('changeDateHTML');
setRngName();
ss.show(html);
}
//getValuesFromForm
function getValuesFromForm(form){
var firstName = form.firstName,
lastName = form.lastName,
reason = form.reason,
newDate = form.datepicker,
city= form.Projects_list.text;
sheet = SpreadsheetApp.getActiveSpreadsheet().getActiveSheet();
SpreadsheetApp.getUi().alert('Test');
sheet.appendRow([lastName, reason, newDate, city]);
var ui = SpreadsheetApp.getUi() ;
alert('Test');
ui.alert('form.Projects_list(0)')
google.script.host.close();
}
// Display the GUI
// Execute this function from the script editor ro run the application.
// Note the call to "setRngName()". This ensures that all newly added
// values are included in the dropdown list when the GUI is displayed
function displayGUI() {
var ss,
html;
setRngName();
ss = SpreadsheetApp.getActiveSpreadsheet();
html = HtmlService.createHtmlOutputFromFile('index').setSandboxMode(HtmlService.SandboxMode.IFRAME);
ss.show(html);
}
// Called by Client-side JavaScript in the index.html.
// Uses the range name argument to extract the values.
// The values are then sorted and returned as an array
// of arrays.
function getValuesForRngName(rngName) {
var rngValues = SpreadsheetApp.getActiveSpreadsheet().getRangeByName(rngName).getValues();
return rngValues.sort();
}
//Expand the range defined by the name as rows are added
function setRngName() {
var ss = SpreadsheetApp.getActiveSpreadsheet(),
sh = ss.getSheetByName('DropdownValues'),
firstCellAddr = 'A2',
dataRngRowCount = sh.getDataRange().getLastRow(),
listRngAddr = (firstCellAddr + ':A' + dataRngRowCount),
listRng = sh.getRange(listRngAddr);
ss.setNamedRange('20Projects', listRng);
//Logger.log(ss.getRangeByName('Cities').getValues());
}
// For debugging
function test_setRngName() {
setRngName();
}
You can use the value attribute.
document.getElementById("Projects_list").value

Pass Object to Templated HTML

I have an object I wold like to pass to a templated HTML file. If I use a simple variable, all is fine, as these work:
on the server side I have the following at the top of code.gs:
//Define this here globally so it is accessed in the HTML Template
var passedFestival = ' ';
var passedSID = ' ';
var passedRID = 'FALSE';
in the HTML file I have:
<script>
var passedFestival = '<?!= passedFestival ?>';
var passedSID = '<?!= passedSID ?>';
var passedRID = '<?!= passedRID ?>';
</script>
I can use these in later code and get the appropriate value. I want to also use an Object, which is the result of reading a couple rows from the spreadsheet, and basically results in the following outside any function, same as the other variables, above:
var testformOptions = [];
testformOptions['currencies'] = [{"currency":"CAD", "default":false, "defaultOption":"Interac", "paymentOptions":"Cheque|Credit Card|Interac|PayPal", "sheetrow":2}, {"currency":"USD", "default":true, "defaultOption":"PopMoney", "paymentOptions":"Cheque|Credit Card|PayPal|PopMoney", "sheetrow":3}];
testformOptions['meals'] = {"use":true, "required":false, "default":"Omnivore", "values":"Omnivore|Vegan"};
in the HTML file I can reference the object's individual values:
if ('<?!= testformOptions.currencyOptions.use ?>') {
$("#currencies").show();
}
But I would rather copy the object over completely and reference it as part of the client side data. I have tried a few things, most of which I understand why they didn't work, but I thought this would:
var formOptions = jQuery.extend(true, {}, <?!= testformOptions?>;
I have tried saving the data to a variable as json, but that didn't work since I have single quotes and other special characters in my final object.
Is there any way to get an object passed into an object on the client side outside using google.script.run to pass it after loading? I am reading the spreadsheet data as part of the initial doGet so I figured it may be faster to use templated HTML and pass the object.
EDIT
Thanks to the reply, I have working code. The final sample reads as follows. Some items are left out to allow focusing on the important parts.
Code.gs:
var passedSID = ' ';
var passedRID = 'FALSE';
function doGet(passed) {
if(passed.parameter.rid && passed.parameter.msid){
// A registration ID and Spreadsheet ID were passed so this is to edit an existing registration
passedSID = passed.parameter.msid;
passedRID = passed.parameter.rid;
var registrationValues = getRegistrationValues(passedSID, passedRID);
}
else if(passed.parameter.msid){
// A Spreadsheet ID was passed so this is to complete a new registration
passedSID = passed.parameter.msid;
}
//get the form options from the appropriate spreadsheet file
//getFormOptions() is from Tutorial: Simple Mail Merge
//https://developers.google.com/apps-script/articles/mail_merge
testformOptions = getFormOptions(passedSID);
//Create the HTML template
var template = HtmlService.createTemplateFromFile('Index');
template.data = JSON.stringify(testformOptions);
// Build and return HTML in IFRAME sandbox mode.
return template.evaluate()
.setTitle('Registration Form').setWidth(620).setXFrameOptionsMode(HtmlService.XFrameOptionsMode.ALLOWALL);
}
function include(filename) {
return HtmlService.createTemplateFromFile(filename).evaluate()
.getContent();
}
Index.html:
<?!= HtmlService.createHtmlOutputFromFile('Stylesheet').getContent(); ?>
<link href="https://fonts.googleapis.com/css?family=Raleway:100" rel="stylesheet">
<html>
<body>
<div id="mybody">
<form>
<!-- Boring form html -->
</form>
</div>
</body>
</html>
<script src="https://code.jquery.com/jquery-3.2.1.min.js"></script>
<script>
var formOptions = $.extend(true, {}, <?!= data ?>);
</script>
<!-- Use a templated HTML printing scriptlet to import JavaScript. -->
<?!= HtmlService.createHtmlOutputFromFile('jquery_cloneform_js').getContent(); ?>
<?!= include('JavaScript'); ?>
And in JavaScript.html:
<script>
var passedSID = '<?!= passedSID ?>';
var passedRID = '<?!= passedRID ?>';
// use onload to call initialization after the document loads
window.onload = setForm;
function setForm(){
var optionArray = [];
var defaultOption = '';
if (formOptions.currencyOptions.use) {
$("#currencies").show();
//Set the options for the currency
var options = formOptions.currencyOptions.values;
defaultOption = formOptions.currencyOptions.defaultOption;
optionArray = options.split("|");
setSelectOptions('regcurrency', optionArray, defaultOption);
var options = formOptions.currencies[1].paymentOptions;
defaultOption = formOptions.currencies[1].defaultOption;
optionArray = options.split("|");
setSelectOptions('paymentMethod', optionArray, defaultOption);
}
}
How about a following answer?
Modification points :
var testformOptions = [];
testformOptions['currencies'] = [{"currency":"CAD", "default":false, "defaultOption":"Interac", "paymentOptions":"Cheque|Credit Card|Interac|PayPal", "sheetrow":2}, {"currency":"USD", "default":true, "defaultOption":"PopMoney", "paymentOptions":"Cheque|Credit Card|PayPal|PopMoney", "sheetrow":3}];
testformOptions['meals'] = {"use":true, "required":false, "default":"Omnivore", "values":"Omnivore|Vegan"};
About the above script, testformOptions is defined as an array. So testformOptions['currencies'] and testformOptions['meals'] cannot be imported. So please modify from var testformOptions = []; to var testformOptions = {};.
When it passes the object, please use JSON.stringify().
The scripts reflected above modifications are as follows.
code.gs :
function doGet() {
var testformOptions = {};
testformOptions['currencies'] = [{"currency":"CAD", "default":false, "defaultOption":"Interac", "paymentOptions":"Cheque|Credit Card|Interac|PayPal", "sheetrow":2}, {"currency":"USD", "default":true, "defaultOption":"PopMoney", "paymentOptions":"Cheque|Credit Card|PayPal|PopMoney", "sheetrow":3}];
testformOptions['meals'] = {"use":true, "required":false, "default":"Omnivore", "values":"Omnivore|Vegan"};
var t = HtmlService.createTemplateFromFile('index');
t.data = JSON.stringify(testformOptions);
return t.evaluate();
}
index.html
<script src="https://code.jquery.com/jquery-3.2.1.min.js"></script>
<p id="disp"></p>
<script>
var data = $.extend(true, {}, <?!= data ?>);
$('#disp').text(JSON.stringify(data));
</script>
Result :
{
"currencies": [
{
"currency": "CAD",
"default": false,
"defaultOption": "Interac",
"paymentOptions": "Cheque|Credit Card|Interac|PayPal",
"sheetrow": 2
},
{
"currency": "USD",
"default": true,
"defaultOption": "PopMoney",
"paymentOptions": "Cheque|Credit Card|PayPal|PopMoney",
"sheetrow": 3
}
],
"meals": {
"use": true,
"required": false,
"default": "Omnivore",
"values": "Omnivore|Vegan"
}
}
If I misunderstand your question, I'm sorry.

how to store the JSON from directive to use it on next HTML page through angular

I have a requirement that i need to read a excel file from any location and to render the data of the excel on the next html page.
I was able to render the excel data with multiple sheets on the same page but now I need to select the file on first page and render its data on the next html page.
Like this:
And on the next screen need to show excel data:
Here in the Sheet Name i need to provide the sheet names from excel and on selecting any sheet name that sheet data need to be loaded in the grid.
I have used two divs to divide the page vertically in two columns.
I was able to achieve this functionality on a single page but now I need to divide this code in multiple pages.
This is the plunker of the work done:
http://plnkr.co/edit/xHEtxtzKrEiKDTrqlafC?p=preview
This is my js code:
angular.module('app', ['ui.grid'])
.controller('MainCtrl', ['$scope', function($scope) {
var vm = this;
vm.gridOptions = {};
vm.reset = reset;
vm.selectedSheet = '';
vm.sheetIndex = 0;
function reset() {
vm.gridOptions.data = [];
vm.gridOptions.columnDefs = [];
vm.selectedSheet = '';
vm.sheetIndex = 0;
}
vm.readSheet = function() {
var workbook = XLSX.read(vm.data, {
type: 'binary'
});
var headerNames = XLSX.utils.sheet_to_json(workbook.Sheets[workbook.SheetNames[vm.sheetIndex]], {
header: 1
})[0];
vm.sheetNames = workbook.SheetNames;
var data = XLSX.utils.sheet_to_json(workbook.Sheets[workbook.SheetNames[vm.sheetIndex]]);
vm.gridOptions.columnDefs = [];
headerNames.forEach(function(h) {
vm.gridOptions.columnDefs.push({
field: h
});
});
vm.gridOptions.data = data;
};
vm.onLoadData = function(data) {
vm.data = vm.data || data;
vm.readSheet();
};
vm.sheetChange = function() {
vm.sheetIndex = vm.sheetNames.indexOf(vm.selectedSheet);
vm.readSheet();
};
}])
.directive("fileread", [function() {
return {
scope: {
onLoadData: '&'
},
link: function($scope, $elm, $attrs) {
$elm.on('change', function(changeEvent) {
var reader = new FileReader();
reader.onload = function(evt) {
$scope.$apply(function() {
$scope.onLoadData({
data: evt.target.result
});
$elm.val(null);
});
};
reader.readAsBinaryString(changeEvent.target.files[0]);
});
}
}
}]);
HTML code:
<!DOCTYPE html>
<html ng-app="app">
<head>
<link data-require="bootstrap-css#*" data-semver="3.3.1" rel="stylesheet" href="//maxcdn.bootstrapcdn.com/bootstrap/3.3.1/css/bootstrap.min.css" />
<script src="http://ajax.googleapis.com/ajax/libs/angularjs/1.3.16/angular.js"></script>
<script src="https://cdn.rawgit.com/SheetJS/js-xlsx/v0.8.0/dist/xlsx.full.min.js"></script>
<script src="https://cdn.rawgit.com/SheetJS/js-xlsx/v0.8.0/dist/ods.js"></script>
<script src="http://cdn.rawgit.com/angular-ui/ui-grid.info/gh-pages/release/3.0.0-rc.22/ui-grid.min.js"></script>
<link rel="stylesheet" href="http://cdn.rawgit.com/angular-ui/ui-grid.info/gh-pages/release/3.0.0-rc.22/ui-grid.min.css" />
<link rel="stylesheet" href="main.css" type="text/css" />
</head>
<body>
<div ng-controller="MainCtrl as vm">
<button type="button" class="btn btn-success" ng-click="vm.reset()">Reset Grid</button>
<br />
<br />
<div id="grid1" ui-grid="vm.gridOptions" class="grid">
<div class="grid-msg-overlay" ng-show="!vm.gridOptions.data.length">
<div class="msg">
<div class="center">
<span class="muted">Select Spreadsheet File</span>
<br />
<input type="file" accept=".xls,.xlsx,.ods" multiple="true" fileread="" on-load-data="vm.onLoadData(data)"/>
</div>
</div>
</div>
<div>
<select ng-model="vm.selectedSheet" ng-options="names as names for names in vm.sheetNames"
ng-change="vm.sheetChange()"></select>
{{vm.selectedSheet}}
</div>
</div>
</div>
<script src="app.js"></script>
</body>
</html>
I think i need to store this JSON somewhere, so that it can be used later in different pages.
Should I use service to achieve this functionality or any other approach need to be used please suggest.
I hope this might help!
You can just store the Json data in to any rootScope variable to use in another controllers.
For Example:
You have the following code;
vm.readSheet = function() {
var workbook = XLSX.read(vm.data, {
type: 'binary'
});
var headerNames = XLSX.utils.sheet_to_json(workbook.Sheets[workbook.SheetNames[vm.sheetIndex]], {
header: 1
})[0];
vm.sheetNames = workbook.SheetNames;
var data = XLSX.utils.sheet_to_json(workbook.Sheets[workbook.SheetNames[vm.sheetIndex]]);
vm.gridOptions.columnDefs = [];
headerNames.forEach(function(h) {
vm.gridOptions.columnDefs.push({
field: h
});
});
vm.gridOptions.data = data;
};
in here
vm.gridOptions.data = data;
you can set and store data for later usage as an JSON Array;
$rootScope.gridOptionsData = data;

google.script.run is not working when using shared script from library

I am working on a script, for which I am calling a function from a library with standalone scripts:
HTML file looks like this:
<!DOCTYPE html>
<html>
<head>
<link rel="stylesheet" href="//ajax.googleapis.com/ajax/libs/jqueryui/1.9.1/themes/cupertino/jquery-ui.css">
<style type="text/css"> .demo { margin: 0px ; color : #AAA ; font-family : arial sans-serif ;font-size : 10pt }
p { color : black ; font-size : 11pt }
.ui-datepicker th {padding:5px;}
.ui-datepicker table {font-size:10px;}
.ui-widget {font-size:12px;}
input{width:100%;}
</style>
<base target="_top">
</head>
<body>
<div class="demo" >
<div style="width:30%;text-align:left;float:left;">
<p> Candidate Email : </p>
<p> Updated Status : </p>
<p> Assigned To :</p>
<p> Date :</p>
</div>
<div style="width:70%;text-align:left;float:left;">
<p> <input class="email" type="text" /></p>
<p><input class="status" type="text" /></p>
<p><input class="assigned" type="text" /></p>
<p><input type="text" name="StartDate" id="startdatepicker" /> </p>
</div>
<input class="submit" type="button" value="Submit" disabled=""/>
</div>
<script src="//ajax.googleapis.com/ajax/libs/jquery/1.9.1/jquery.min.js"></script>
<script src="//ajax.googleapis.com/ajax/libs/jqueryui/1.9.1/jquery-ui.min.js"></script>
<script>
$(document).ready(function(){
$(".email").val(email);
$(".status").val(status);
$(".assigned").val(assigned);
$(document).on('click','input.submit',function(){
submitDates();
});
$( "#startdatepicker" ).datepicker({
showWeek: true,
firstDay: 0,
});
$(document).on('change','#startdatepicker',function(){
if($("#startdatepicker").val()!='')
{
$("input.submit").removeAttr("disabled");
}
else {
$("input.submit").attr("disabled","true");
}
});
});
</script>
<script>
function submitDates() {
var startDate = $("#startdatepicker").val();
var email = $(".email").val();
var status = $(".status").val();
var assigned = $(".assigned").val();
google.script.run
.withSuccessHandler(
// Dates delivered, close dialog
function() {
google.script.host.close();
})
// Display failure messages
.withFailureHandler(
function() {
var div = $('<div id="error" class="error">' + "Please enter the correct Date" + '</div>');
div.after($("#demo"));
})
.statusLogger(email, status, assigned, startDate);*/
}
</script>
</body>
</html>
And gs file looks like this:
function onEdit(event) {
var lSheet = SpreadsheetApp.getActive().getSheetByName("Status Logs");
var sheet = event.source.getSheetByName('Tracker');
var actRng = event.source.getActiveRange();
var editColumn = actRng.getColumn();
var index = actRng.getRowIndex();
var headers = sheet.getRange(1, 1, 1, sheet.getLastColumn()).getValues();
var dateCol = headers[0].indexOf("Status Change Date");
var updateCol = headers[0].indexOf("Application Status");
var emailCol = headers[0].indexOf("Email");
var assignCol = headers[0].indexOf("Assigned To");
var intType = sheet.getRange(index,updateCol+1).getValue();
var email = sheet.getRange(index,emailCol+1).getValue();
var assignedTo = sheet.getRange(index,assignCol+1).getValue();
if (dateCol > -1 && index > 1 && editColumn == updateCol+1) {
//lSheet.appendRow([email, intType, sheet.getRange(index, dateCol + 1).getValue(),assignedTo]);
var html = HtmlService.createHtmlOutputFromFile('dateDialogue')
.setWidth(300)
.setHeight(200)
.getContent();
var html2 = HtmlService.createHtmlOutput(html + '<script>var email= "'+ email +'";var status="'+ intType +'";var assigned="'+ assignedTo +'";</script>');
SpreadsheetApp.getUi()
.showModalDialog(html2, 'Please enter the Date');
}
}
statusLogger function just append a row in a sheet.
The issue is, google.script.run is not working although google.script.host.close() is working. Any help?
From your question I am concluding you have 2 scripts. One is a document bound script and the another one is stand alone script included in your document bound script as a library.
When you add a script in your project as a library you assign an identifier to it. The library functions can then be called from code.gs using this identifier.
Example:
I have a stand alone script named stackflow which I included in my project as an external library.
The identifier I gave to the library is stackflow
In my standalone script (which is included as a library)
function testLibraryFunction(){
return "successful execution of library function";
}
In my actual project I will try to access library function like this
code.gs
function executeLibraryCode(){
var result = stackflow.testLibraryFunction();
Logger.log(result);
return result
}
In my html file, I will call executeLibraryCode() which will call testLibraryFunction() function from library.
HTML file:
google.script.run
.withSuccessHandler(
// callback function
)
.withFailureHandler(
// callback function
)
.executeLibraryCode();
Also please remove */ from your html file after .statusLogger as mentioned by #ocordova in the comments.