Google Apps Script passing parameter to google.script.run - javascript

Can not pass parameter from Page.html file to google.script.run function
<input type="button" value="Load Norm"
onclick="google.script.run
.loadNormFromSidebar('10A')" />
Then I am expecting to have 10A as parameter to my loadNormFromSidebar function:
function loadNormFromSidebar(normNr) {
Logger.log(normNr);
var jobNr = params.getDescriptionSheet().getRange(params.jobNrCell).getValue();
normNr=jobNr+'-'+normNr;
loadNormWithNr(normNr);
}
Any ideas why normNr is not passed from html to gs?
Log output file is empty.

I can not reproduce the problem. In my test everything works as expected.
Index.html
<html>
<body>
<input type="button"
value="Load Norm"
onclick="google.script.run.loadNormFromSidebar('10A')" />
</body>
</html>
Code.gs
function doGet(e) {
var template = HtmlService.createTemplateFromFile('Index');
return template.evaluate()
.setTitle('Web App Window Title')
.setSandboxMode(HtmlService.SandboxMode.IFRAME);
}
function loadNormFromSidebar(normNr) {
Logger.log(normNr);
/*
var jobNr = params.getDescriptionSheet().getRange(params.jobNrCell).getValue();
normNr=jobNr+'-'+normNr;
loadNormWithNr(normNr);
*/
}
View -> Logs
Have you created a new version of your application and published that version?

Found mistake. Above code is part of library Estimating. In local file I had
function loadNormFromSidebar() {
Estimating.loadNormFrimSidebar()
}
where should be
function loadNormFromSidebar(normNr) {
Estimating.loadNormFrimSidebar(normNr)
}

Related

Google apps script html to spreadsheet

I am learning google apps script at the moment by myself.
I have been trying to get someone's mail and append it to a google spreadsheets.
My code.gs looks actually like this:
function doGet() {
return HtmlService.createHtmlOutputFromFile("page");
};
function addEmail (mail) {
var mysheet = SpreadsheetApp.openById("1k3vWmg9859mYykNNl0xDWoR_LUhnvLlq1qW8kSRuL_Q").getSheetByName("Sheeet1");
mysheet.appendRow(mail);
};
And my html file looks like this:
<html>
<head>
<base target="_top">
</head>
<body>
<h1>hello</h1>
</body>
<label for="getUserMail">Type your mail here</label> <input type="text" id="getUserMail">
<button id="trigger">Submit!</button>
<script>
document.getElementById("trigger").addEventListener("click",sendMailToCode);
function sendMailToCode () {
var umail = document.getElementById("getUserMail");
google.script.run.addEmail(umail);
};
</script>
</html>
But it doesn't work. I have tried doing multiple stuff to fix it, even adding a tag on html but it does not save the value on the spreadsheet. Could someone please give an advice?
Try this:
This will append the html to the sheet but it will not render it.
function addEmail (mail='<html><head><basetarget="_top"></head><body><h1>hello</h1></body><labelfor="getUserMail">Typeyourmailhere</label><inputtype="text"id="getUserMail"><buttonid="trigger">Submit!</button><script>document.getElementById("trigger").addEventListener("click",sendMailToCode);functionsendMailToCode(){varumail=document.getElementById("getUserMail");google.script.run.addEmail(umail);};</script></html>') {
var ss = SpreadsheetApp.getActive();
const sh = ss.getSheetByName('Sheet0');
sh.appendRow([mail]);
}
appendRow
Reading the description of row contents: "An array of values to insert after the last row in the sheet."

Pass value from HTML to Google Script on Google Apps Script?

I need to pass a data value from the HTML to the Google Script on a GAS project. The parts with comments of the code is the value I need to pass.
gs file
function doGet(e) {
if (e.parameter.prefix){
var result = data; // <-- GET VALUE "data" FROM THE HTML "forms.html"
var content = e.parameters.prefix + '(' +JSON.stringify(result) + ')';
return ContentService.createTextOutput(content)
.setMimeType(ContentService.MimeType.JAVASCRIPT);
}
var html = HtmlService.createHtmlOutputFromFile('Index');
return html.setXFrameOptionsMode(HtmlService.XFrameOptionsMode.ALLOWALL);
}
Index.html in GAS project
<!DOCTYPE html>
<html>
<head>
<base target="_top">
</head>
<body>
<h1 id='title' style="color: #e31414">SCRIPT</h1>
<h1 id='done' style="display: none"> DATA PASSED</h1>
<button id="btn" onclick="passData()">Run "passData()"</button>
</body>
</html>
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/2.2.0/jquery.min.js"></script>
<script>
function passData() {
$('#done').show();
var data = 'value'; //<-- PASS THIS DATA TO GOOGLE SCRIPT (The .gs file)
}
</script>
Follow these steps:
in the gs file, create a variable without a value at the very top: var data;
Create a function below it like so:
function myfunction(x) {
data = x;
}
in the Index.html file especially in passData() function, insert this line in the bottom of the function: google.script.run.myfunction(data);
Finally, you will be able to use the result variable as the data in doGet() function.
-- your code should look like this --
gs file
var data;
function myfunction(x) {
data = x;
}
function doGet(e) {
if (e.parameter.prefix){
var result = data; // <-- GET VALUE "data" FROM THE HTML "forms.html"
var content = e.parameters.prefix + '(' +JSON.stringify(result) + ')';
return ContentService.createTextOutput(content)
.setMimeType(ContentService.MimeType.JAVASCRIPT);
}
var html = HtmlService.createHtmlOutputFromFile('Index');
return html.setXFrameOptionsMode(HtmlService.XFrameOptionsMode.ALLOWALL);
}
Index.html in GAS project
<!DOCTYPE html>
<html>
<head>
<base target="_top">
</head>
<body>
<h1 id='title' style="color: #e31414">SCRIPT</h1>
<h1 id='done' style="display: none"> DATA PASSED</h1>
<button id="btn" onclick="passData()">Run "passData()"</button>
</body>
</html>
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/2.2.0/jquery.min.js"></script>
<script>
function passData() {
$('#done').show();
var data = 'value'; //<-- PASS THIS DATA TO GOOGLE SCRIPT (The .gs file)
google.script.run.myfunction(data);
}
</script>

Google Apps Script - return output from apps script function back to the html file javascript function

Ok, so I am trying to make a function in google sheets that when the user selects a cell and then runs the function (currently trying to make), a sidebar getting all the synonyms of the word should appear. I am using https://words.bighugelabs.com/ to get the synonyms. So first I make the menu:
`function onOpen(e) {
var ui = SpreadsheetApp.getUi().createMenu("Sidebar")
.addItem("Get Synonym", 'showSidebar')
.addToUi();
}`
Then this is the showSidebar function:
function showSidebar() {
var html = HtmlService.createHtmlOutputFromFile("Test")
.setSandboxMode(HtmlService.SandboxMode.IFRAME)
.setWidth(150)
.setTitle("My Sidebar");
SpreadsheetApp.getUi().showSidebar(html);
}
This is the html file:
<!DOCTYPE html>
<html>
<head>
<base target="_top">
<script>
function doSomething() {
var synonyms = google.script.run.getSynonym();
document.getElementById("synonyms").innerHTML = synonyms;
}
</script>
</head>
<body>
<div>
<span style="color:orange;">This is a test sidebar!</span>
<button onclick="doSomething()">Click Me!</button>
<div id="synonyms"></div>
</div>
</body>
</html>
And this is the getSynonym function:
function getSynonym() {
var word = SpreadsheetApp.getActiveRange().getValue();
var synonyms = [];
var response = UrlFetchApp.fetch("http://words.bighugelabs.com/api/2/{my_api_key}/" + word + "/json");
response = JSON.parse(response);
var synonyms = response.adjective.syn;
return synonyms;
}
But the variable synonyms which as an array of synonyms doesn't get returned to the doSomething function in the Html file.
What I want is that the sidebar should get a list of all the synonyms.
So basically I can't get the data from one function to another...and I want to know if this is the right way.
When calling server side functions using google.script.run you need to define a success handler, which will asynchronously receive your response.
See the examples on: https://developers.google.com/apps-script/guides/html/communication
function onSuccess(synonyms ) {
console.log(synonyms);
}
google.script.run.withSuccessHandler(onSuccess).doSomething();

Button Clicked true or false - JavaScript

I am a Bit Beginner In JavaScript. So I need a code about { If we clicked a button a function need to run} more of them suggested this but it still not working ! and I don`t know why? Can you solve it?
if(document.getElementById("btn").clicked == true){
//some code here
console.log("working");
}
<button id=""btn>ClickEvent</button>
Do not use the if. if statement is executed on page load.
Instead, use Onclick() for example :
var data = "";
function clickBtn() {
if(data != "")
document.getElementById("result").innerHTML = "Hello World !";
else
getData();
}
function getData() {
data = "Hello World !";
}
<button onclick="clickBtn()">Click me</button>
<p id="result"></p>
Good question, lets use the an HTML file that references a JavaScript.
So the first file lets call it webpage.html
<!DOCTYPE html>
<html>
<head>
<script src="script.js"></script>
</head>
<body>
<input type="button" value="save" onclick="save()"></input>
<input type="button" value="display" onclick="print()"></input>
<div id="area"></div>
</body>
</html>
And the second file script.js
function save()
{
StringTest="Hello world";
}
function print()
{
document.getElementById("area").innerHTML=StringTest;
}
The approach might be a little different but this is recommended as you would more control over the elements in the script.
For example:
<input type="button" will tell the script that it is a form input of the type button whose click will call the function print() in the JavaScript
document.getElementById("area")captures the elements that we define from the Document Object Model(DOM)

How to apply this example to my already existing line of code?

Currently I'm using an example to create an upload function for my webpage on Google Apps Script. This is the code:
Code.gs
function doGet(e) {
return HtmlService.createHtmlOutputFromFile('form.html');
}
function uploadFiles(form) {
try {
var dropbox = "Test Files";
var folder, folders = DriveApp.getFoldersByName(dropbox);
if (folders.hasNext()) {
folder = folders.next();
} else {
folder = DriveApp.createFolder(dropbox);
}
var blob = form.myFile;
var file = folder.createFile(blob);
file.setDescription("Uploaded by " + form.myName);
return "File uploaded successfully " + file.getUrl();
} catch (error) {
return error.toString();
}
}
form.html
<form id="myForm">
<input type="text" name="myName" placeholder="Your name..">
<input type="file" name="myFile">
<input type="submit" value="Upload File"
onclick="this.value='Uploading..';
google.script.run.withSuccessHandler(fileUploaded)
.uploadFiles(this.parentNode);
return false;">
</form>
<div id="output"></div>
<script>
function fileUploaded(status) {
document.getElementById('myForm').style.display = 'none';
document.getElementById('output').innerHTML = status;
}
</script>
<style>
input { display:block; margin: 20px; }
</style>
This code works fine by itself but when I try and implement it on my webpage with the current existing code: https://jsfiddle.net/05nmqy63/
It won't work like shown in the example. The example uploads a file into a folder in my Google Docs but when put into my code the page changes but it doesn't upload anything nor does it say the file has been submitted.
How do I fix this? Or is there an easier way to implement an upload button? (I want the submit order button to be able to function as the upload button)
Figured out the problem to my question after finding out what was wrong. The error I received was this: Uncaught InvalidArgumentError: Failed due to illegal value in property: 0
This error was solved by another person on this forum: google.script.run not working: Uncaught InvalidArgumentError: Failed due to illegal value in property: 0

Categories

Resources