how to put a variable into GAS - javascript

Hi so i've been trying to code in Jquery javascript html and google apps script and i have gotten part of the app but i can't do the other half which is to take the jquery variable and print it in a google spread sheet. This is what it looks like right now.
GAS:
function doGet() {
return HtmlService.createTemplateFromFile('index')
.evaluate()
.setTitle('The Game')
.setSandboxMode(HtmlService.SandboxMode.IFRAME);
}
function codefunction() {
Logger.log("In codefunction in codegs");
}
HTML:
<!DOCTYPE html>
<html>
<head>
<base target="_top">
</head>
<body>
<h1> The Game </h1>
<b><em>Output:</em></b>
<p id="output">
</p>
<input type="text" id="txt_box"/>
<button type="button" id="input_button" class="enjoy-css">Enter</button>
<?!= HtmlService.createHtmlOutputFromFile('javascript').getContent(); ?>
</body>
</html>
Jquery/javascript:
<script>
$(function() {
$('#input_button').bind('click',clickButton);
linkTocodegs();
});
function clickButton() {
var boxContents = $("#txt_box").val();
$("#txt_box").val("");
outputMessage(boxContents);
}
function outputMessage(message) {
var text = $('#output');
var item = $('<p>');
var title = $('<span>').text(message);
title.append(item);
text.append(title);
}
function linkTocodegs() {
console.log("in code gs function link");
google.script.run.withSuccessHandler(outputMessage)
.codefunction();
}
</script>

You need to get the value out of the text box and pass it to the server:
function linkTocodegs() {
var userInput;
userInput = document.getElementById('txt_box').value;
console.log("in code gs function link");
google.script.run.withSuccessHandler(outputMessage)
.codefunction(userInput);
}
Code.gs
function codefunction(receivedValue) {
Logger.log("In codefunction in codegs: " + receivedValue);
var ss,sh;
ss = SpreadsheetApp.getActiveSpreadsheet();
sh = ss.getSheetByName('sheet1');
sh.getRange(1,1,1,1).setValue(receivedValue);
}

Related

How to read and print PropertiesServices from client-side HTML with Google Apps Script?

The foo variable is sent from the client side HTML to Code.js as demonstrated by the logs. When this occurs, the bar key from PropertiesService is set and logged.
How is PropertiesServices accessed from the client side HTML and output as text?
logs:
Cloud logs
Oct 15, 2022, 5:27:14 PM
Info
logProperties..
Oct 15, 2022, 5:27:14 PM
Info
bar
Oct 15, 2022, 5:27:14 PM
Info
foo
Oct 15, 2022, 5:27:14 PM
Info
sending foo
html:
<!DOCTYPE html>
<html>
<head>
<base target="_top">
<script>
function sendFoo()
{
var foo = document.getElementById("foo").value;
google.script.run.setBar(foo);
document.getElementById("foo").value = '';
}
</script>
</head>
<body>
foo is:<input type="text" id="foo" />
<input type="button" value="sendFoo" onclick="sendFoo()" /> <br> <br> <br>
bar is:
</body>
</html>
I believe this can be accomplished with span tag.
code:
function setBar(foo) {
PropertiesService.getScriptProperties().setProperty("foo",foo);
PropertiesService.getScriptProperties().setProperty("bar","foo received");
logProperties();
}
function initProperties() {
PropertiesService.getScriptProperties().deleteAllProperties();
}
function logProperties() {
Logger.log("logProperties..");
var keys = PropertiesService.getScriptProperties().getKeys();
keys.forEach(key => {
Logger.log(key);
Logger.log(PropertiesService.getScriptProperties().getProperty(key));
});
}
function getUrl() {
var url = ScriptApp.getService().getUrl();
return url;
}
function doGet(e) {
initProperties();
var htmlOutput = HtmlService.createTemplateFromFile('WebApp');
htmlOutput.url = getUrl();
return htmlOutput.evaluate();
}
This is just within Google Apps Script and has been kept as simple as possible, but no simpler.
see also:
https://codewithcurt.com/how-to-call-google-apps-script-function-from-web-app/
Less than perfect, but accomplishes the main goal of getting data from server and displaying client side when requested by the client.
code:
var sheetId = "1L3Sd-J780mQtb7JYsmJzInI1kMdrQA8GbLspQJ5eVW4";
var sheetName = "data";
function doGet(e) {
return HtmlService.createHtmlOutputFromFile('WebApp');
}
function getOneCellData() {
Logger.log("getOneCellData..");
var ss = SpreadsheetApp.openById(sheetId);
var sheet = ss.getSheetByName(sheetName);
var data = sheet.getRange(1,1,1,1).getValue();
return data;
}
function getMultiCellData() {
var ss = SpreadsheetApp.openById(sheetId);
var sheet = ss.getSheetByName(sheetName);
var data = sheet.getRange('A1:C1').getValues();
return data;
}
function getInOutData(inData) {
Logger.log("getInOutData");
var outData = "IN DATA: " + inData;
return outData;
}
html:
<!DOCTYPE html>
<html>
<head>
<base target="_top">
<script>
function callOneCellData()
{
google.script.run.withSuccessHandler(function(returnData)
{
document.getElementById("oneCellData").innerHTML = returnData;
}).getOneCellData();
}
function callMultiCellData()
{
google.script.run.withSuccessHandler(function(returnArray)
{
console.log(returnArray);
var stringArray = returnArray.toString();
document.getElementById("multiData").innerHTML = stringArray;
}).getMultiCellData();
}
function callInOutData()
{
var inData = document.getElementById("inData").value
google.script.run.withSuccessHandler(function(outData)
{
document.getElementById("outData").innerHTML = outData;
}).getInOutData(inData);
}
function callData()
{
callOneCellData();
callMultiCellData();
callInOutData();
}
</script>
</head>
<body>
<label>One Cell Data</label><br><textarea id="oneCellData" ></textarea><br>
<label>Multi Data</label><br><textarea id="multiData" ></textarea><br>
<label>In Data</label><br><input type="text" id="inData" /><br>
<label>Out Data</label><br><textarea id="outData" ></textarea><br>
<input type="button" onclick="callData()" value="Get Data" />
</body>
</html>
I had thought this was best done with Properties but that may not be so.
Ideally, would display the above textarea as just "plain" text.

function won't run when executed from htmlService?

Im trying to switch my current sheet after 5s of the htmlService modalDialog opening.
For some reason SwitchToSheet1() does not work...
.gs
function openModal() {
var ui = SpreadsheetApp.getUi();
var html = HtmlService.createTemplateFromFile('BarcodeLoadingHTML')
.evaluate()
.setWidth(400)
.setHeight(250);
ui.showModalDialog(html, "‎");
}
function SwitchToSheet1() {
var spreadsheet = SpreadsheetApp.getActiveSpreadsheet();
spreadsheet.setActiveSheet(spreadsheet.getSheetByName('Bestandsliste'), true);
};
BarcodeLoadingHTML.html
<!DOCTYPE html>
<html>
<head>
<base target="_top">
<?!= include('jQuery'); ?>
<?!= include('Stylesheet'); ?>
<?!= include('lottieplayer'); ?>
</head>
<body>
<div id="loading">
<lottie-player id="lottie-load" src="https://static.staticsave.com/lottie/cloudupload.json"
background="transparent"
speed="1"
loop
autoplay>
</lottie-player>
<lottie-player id="lottie-success" src="https://assets3.lottiefiles.com/private_files/lf30_qXYuJE.json"
background="transparent"
speed="1">
</lottie-player>
<p class="loadingtext" id="text">Bitte warten<span>.</span><span>.</span><span>.</span></p>
</div>
<script>
$(window).ready(setTimeout (function() {
$('#lottie-load').hide()
$('#text').text('Upload Erfolgreich!')
$('#lottie-success').fadeIn()
$('#lottie-success').get(0).play();
}, 2500));
$(window).ready(setTimeout (function() {
google.script.run.SwitchToSheet1();
google.script.host.close();
}, 5000));
</script>
</body>
</html>
Replace
google.script.run.SwitchToSheet1();
google.script.host.close();
by
google.script.run
.withSuccessHandler(() => google.script.host.close())
.SwitchToSheet1();
The above because google.script.host.close() is executing before google.script.run.SwitchToSheet1(). This happens because calls to server code using google.script.run are asynchronous, in other words, the Google servers not all the time responds instantly when they are called by run, so google.script retry until the server responds, but if the dialog is closed, there aren't more attempts to call the server.
Related
Auto close modal dialog - After server code is done, close dialog in Google Spreadsheet
Modal dialog doesn't write back to sheet, when google.script.host.close() is used
FWIW, assuming I have a spreadsheet with two sheets named Sheet1 and Sheet2, and Sheet2 is the active, the following code works for me:
// Code.gs
function showDialog() {
const html = HtmlService.createHtmlOutputFromFile('page')
.setWidth(400)
.setHeight(400);
SpreadsheetApp.getUi().showModalDialog(html, 'My custom dialog');
}
function SwitchToSheet1() {
var spreadsheet = SpreadsheetApp.getActiveSpreadsheet();
var sh = spreadsheet.getSheetByName('Sheet1');
spreadsheet.setActiveSheet(sh, true);
};
And the HTML page:
<!DOCTYPE html>
<html>
<head>
<base target="_top">
</head>
<body>
<script>
window.addEventListener('DOMContentLoaded', () => {
setTimeout (function() {
google.script.run.SwitchToSheet1();
google.script.host.close();
}, 5000)
})
</script>
</body>
</html>

Creating a very simple Dynamic Google Script Web App

OK I'm stuck at the beginning of setting up a dynamic stand-alone google script. I can't get the button to make any dynamic change to the html. I would figure that clicking the button will call the google script code function and would make a change to the resulting Index.html. What am I missing?
Code.gs:
function doGet() {
return HtmlService
.createHtmlOutputFromFile('Index')
.setTitle('DynamicTest');
}
function DoSomething() {
var obj = document.getElementById("status");
alert("kachow");
obj.innerText = "It's magic!";
}
Index.html
<!DOCTYPE html>
<html>
<body>
<button id="submitButton">Submit</button>
<br />
<div id="status">Static</div>
<br />
<script>
document.getElementById('submitButton').addEventListener('click', function() {
google.script.run.DoSomething();
});
</script>
</body>
</html>
Thanks!
Update Solution: Thanks #Tanaike for the solution! Here is the full code which also adds an pre-processing message as well as a post-processing message that is displayed after the google script app finishes the called function:
<!DOCTYPE html>
<html>
<body>
<button id="submitButton">Submit</button>
<br />
<div id="status">Static</div>
<br />
<script>
document.getElementById('submitButton').addEventListener('click', function() {
var obj = document.getElementById('status');
obj.innerText = 'Processing. Please wait...';
google.script.run.withSuccessHandler(value => {
var obj = document.getElementById("status");
obj.innerText = value;
}).DoSomething();
});
</script>
</body>
</html>
Code.gs
function doGet() {
return HtmlService
.createHtmlOutputFromFile('Index')
.setTitle('DynamicTest');
}
function DoSomething() {
return "It's magic!";
}
Modification points:
In your script, it seems that DoSomething() is not Google Apps Script. I think that it's Javascript. I think that this is the reason of your issue. So when the following modification is done, I think that the script works.
<!DOCTYPE html>
<html>
<body>
<button id="submitButton">Submit</button>
<br />
<div id="status">Static</div>
<br />
<script>
document.getElementById('submitButton').addEventListener('click', function() {
// google.script.run.DoSomething();
DoSomething();
});
function DoSomething() {
var obj = document.getElementById("status");
alert("kachow");
obj.innerText = "It's magic!";
}
</script>
</body>
</html>
But I thought that you might want to communicate between Javascript side and Google Apps Script. So in this case, please modify as follows.
Modified script:
Code.gs:
function doGet() {
return HtmlService
.createHtmlOutputFromFile('Index')
.setTitle('DynamicTest');
}
function DoSomething() {
return "It's magic!";
}
Index.html:
<!DOCTYPE html>
<html>
<body>
<button id="submitButton">Submit</button>
<br />
<div id="status">Static</div>
<br />
<script>
document.getElementById('submitButton').addEventListener('click', function() {
google.script.run.withSuccessHandler(value => {
var obj = document.getElementById("status");
alert("kachow");
obj.innerText = value;
}).DoSomething();
});
</script>
</body>
</html>
Reference:
Class google.script.run

how to get value by an input in one textbox from another column the same row

i've have an html file with two textboxes
1.orders
1.amount
i want that when i type a number in the orders text box
i will get the value from another column in my Google Sheet in the same row that match to to this order
this is my Code.gs code its not working
function doGet(e) {
return HtmlService.createHtmlOutputFromFile('page');
}
function getCost(oneCode){
var url = "https://docs.google.com/spreadsheets/d/1333t7lvECnmOcCnTE6gnn_RN1wrPckWpIETiPUjkUnU/edit#gid=0";
var ss = SpreadsheetApp.openUrl(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]; });
var amountList = data.map(function(r){ return r[1]; });
var position = ordersLis.indexOf(oneCode);
if(position > -1){
return amountList[position];
} else {
return "not found";
}
}
========================
this the html code
<!DOCTYPE html>
<html>
<head>
<base target="_top">
</head>
<script>
document.getElementById("one").addEventlistener("input",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>
I would like to propose the following modification.
Modification points:
At HTML&Javascript side,
addEventlistener is addEventListener.
When your script is used, please modify document.getElementById("one").addEventListener("input",doThis); to as follows. Because when document.addEventListener("DOMContentLoaded", function) is not used, an error occurs at addEventListener.
document.addEventListener("DOMContentLoaded", function(){
document.getElementById("one").addEventListener("input",doThis);
});
When input is used as the event type, when the inputted text is 130, 1, 13 and 130 are sent. By this, google.script.run.withSuccessHandler(updateAmount).getCost(oneCode) is run 3 times. So I think that change might be suitable for this situation.
At Google Apps Script side,
At var ss = SpreadsheetApp.openUrl(url);, openUrl is openByUrl.
I think that in your script, var position = ordersLis.indexOf(oneCode); is var position = ordersList.indexOf(oneCode);.
In your script, oneCode of getCost(oneCode) is the string type.
When above points are reflected to your script, it becomes as follows.
Modified script:
HTML&Javascript side:
<!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>
When <script>###</script> is bottom of HTML, I think that document.addEventListener("DOMContentLoaded", function() {}) is not required to be used.
Google Apps Script side:
function doGet(e) {
return HtmlService.createHtmlOutputFromFile('page');
}
function getCost(oneCode){
var url = "https://docs.google.com/spreadsheets/d/1333t7lvECnmOcCnTE6gnn_RN1wrPckWpIETiPUjkUnU/edit#gid=0";
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";
}
Usage:
From your script, it seems that you are using Web Apps. When you use this script, please copy and paste the above scripts to the script editor, and please redeploy the Web Apps as new version. By this, the latest script is reflected to Web Apps. Please be careful this.
When the Web Apps is opened, please input a value to the input box and push the enter key or remove the focus from the input box. By this, addEventListener("change", doThis) is executed and doThis is run.
References:
addEventListener()
openByUrl(url)
Web Apps

How to get data from Google Spreadsheet to HTML as a javascript variable?

I am trying to create webapp with html service. Here is my code.
The code in code.gs file.
function doGet() {
return HtmlService
.createTemplateFromFile('userendhtml')
.evaluate();
}
function getData() {
var sss = SpreadsheetApp.openById('xxxx');
var rawData = sss.getDataRange().getValues()
var data = []
for (var i = 0; i< rawData.length; i++){
data.push(rawData[i])
}
return data
}
Now I want to access this data as javascript variable for further processing (for creating table with querying). The code in userendhtml.html is
<!DOCTYPE html>
<html>
<head>
<base target="_top">
</head>
<body>
<script>
var data2 = getData();
</script>
</body>
</html>
This doesn't store data to variable data2. So how to get data from spreadsheet in variable in javascript?
You want to use google.script.run in conjunction with withSuccessHandler(...)
<!DOCTYPE html>
<html>
<head>
<base target="_top">
</head>
<body>
<script>
var data2;
google.script.run.withSuccessHandler(function(ret){
data2 = ret;
}).getData();
</script>
</body>
</html>
You could use the techniques found in the Templated Html reference that I gave you. But you could also do this:
<script>
var data2;
window.onload=function(){
google.script.run
.withSuccessHandler(function(dt){
data2=dt;
document.getElementById('myDiv').innerHTML=data2;
.getData();
}
</script>
The templated html approach loads on the server and this approach loads after the dom loads.
I just tested this example as a dialog
function dialogTest() {
var html='<div id="mydiv"></div>';
html+='<script>var data2;window.onload=function(){google.script.run.withSuccessHandler(function(dt){data2=dt;document.getElementById("mydiv").innerHTML=data2;}).getMtData();}</script>';
SpreadsheetApp.getUi().showModelessDialog(HtmlService.createHtmlOutput(html), 'Dialog Test');
}
function getMtData() {
return 'Hello World';
}

Categories