Sending input from HTML using callback - google-apps-script

I have the code for the input from a user, and I have the callback, I am just confused on how to have the data sent using the callback
my code:
HTML
<!DOCTYPE html>
<html>
<head>
<base target="\_top">
</head>
<body>
<label>User info: </label>
<div align="justify">
<input type= "text" id = "email">
</div>
<br>
<button id="searchData"> Search data sheet </button>
<script>
//Above creates a box for user input [//document.getElementById](//document.getElementById)("searchData").addEventListener("click",addHeaders); document.getElementById("searchData").addEventListener("click",google.script.run.withSuccessHandler(onSuccess).testCase());
//gets the button1 element and listens for a click then runs the function addName.
function onSuccess(numUnread) {
var div = document.getElementById('output');
div.innerHTML = numUnread
} ​
google.script.run.withSuccessHandler(onSuccess).testCase()
</script>
</body>
</html>
Apps Script
function doGet() {
return HtmlService.createHtmlOutputFromFile('frontEnd');
}
function testCase(input)
{
Logger.log((input + ' hello'))
return (input + ' hello')
}
My expected would be the input + " hello", instead I got "undefined hello"

Let's say that in your html you have a button like this with a div above it:
<body>
<div id="message"></div>
<input type="button" value="Hello" onClick="sayHello();" />
<script>
//When you click the button this function gets called
function sayHello() {
google.script.run
.withSuccessHandler(function(msg){
document.getElementById("message").innerHTML=msg;//message will appear in the div
})
.sayHelloToServer();//This function is on the server
console.log('My Code');
</script>
</body>
Then in Code.gs:
function sayHelloToServer() {
return "Hello. We're very happy that you came to visit us.";//this is returned to withSuccessHandler(function(msg){}) or you can also use a standalone function in which you simply put its name in like this .withSuccessHandler(funcname)
}
This is explained in Client to Server Communication

Related

Uploading An Image With Google Apps Script To A GSheet - Passing Values To And From HTML Service Modal Dialog

I'm trying to trigger a file upload off of a Google Sheet, taking the uploaded file, add it to a Google Drive folder, and then return the URL of the uploaded file and place it in a cell on the Sheet. I'm currently triggering the file upload by using a checkbox. Once you set the checkbox to TRUE, it'll pop up a dialog box with a file upload input field. This is triggered by an installed onEdit function. Also, info on the row in the sheet will be used to name the newly uploaded file. This info will be input manually on the sheet.
I get to the showModalDialog line, and the dialog box comes up just fine, but I can't figure out how to pass variables from the original function to the HTML service and then back again (with the file) to upload to Drive, set the name, and put the URL back on the sheet.
Here's the first function in Code.gs, receiving values from the onEdit function:
function addFile(ss,ui,row,total) { \\Triggered if edited cell is in column 25 & value is TRUE
Logger.log('add file function');
var name = ss.getRange(row,1).getDisplayValue();
var date = ss.getRange(row,3).getDisplayValue();
var filename = 'Row ' + row + ' - ' + name + ' - ' + date + ' - ' + total;
var htmlTemp = HtmlService.createTemplateFromFile('Index');
htmlTemp.fName = filename;
htmlTemp.position = row;
var html = htmlTemp.evaluate().setHeight(76).setWidth(415);
ui.showModalDialog(html, 'Upload');
Logger.log('end of add file function');
}
And here's what's in Index.html:
<!DOCTYPE html>
<html>
<head>
<base target="_center">
<link rel="stylesheet" href="https://ssl.gstatic.com/docs/script/css/add-ons1.css">
</head>
<body>
<form>
Please upload image below.<br /><br />
<input type="file" name="upload" id="file" accept="image/*,.pdf" />
<input type="button" value="Submit" class="action" onclick="formData(this.parentNode)" />
<input type="button" value="Close" onclick="google.script.host.close()" />
</form>
<script>
function formData(obj){
var newFileName = <? fName ?>;
var rowNum = <? position ?>;
google.script.run.withSuccessHandler(closeIt).upload(obj,newFileName,rowNum);
}
function closeIt(e){
console.log(e);
google.script.host.close();
};
</script>
</body>
</html>
And here's the return function on Code.gs:
function upload(obj,newFileName,rowNum) {
Logger.log('upload function');
var upFile = DriveApp.getFolderById('[folderid]').createFile(obj).setName(newFileName);
var fileUrl = upFile.getUrl();
Logger.log(fileUrl);
var urlCell = SpreadsheetApp.getSheetByName('sheet name').getRange(rowNum,26);
urlCell.setValue('=HYPERLINK("' + fileUrl + '","View image")');
}
Running this code, the dialog box comes up just fine, and I'm able to select a file for upload. However, clicking the Submit button does nothing, and the box stays up until I X it out or hit the Cancel button. The logs only get so far as 'end of add file function' and never gets to the upload function. Should the google.script.run.withSuccessHandler line close the dialog box, or is something else needed to confirm / get the file and close the box?
I've been searching online and have found a number of posts relating to this, but none seem to address this specific issue. This is also pretty much a frankenstein of code I've cobbled together from those posts, so it's possible there's just something that doesn't belong in there and if that is the case I do apologize. Any help would be appreciated; thanks!
[Edit: the submit button wasn't opening a separate tab because I was using <input type="button"> instead of <button>.]
According to the documentation [1] in the “Parameters and return values” part,
if you’re going to send the form object as a parameter “it must be the function’s only parameter”. So you should send the parameters inside the form, using inputs of types “hidden” or “text”, then, from code.gs you can retrieve the input data of the Form object.
Another thing stated in the documentation [1] in the “form” section, is that you need to disable the default submit action with preventFormSubmit function.
Another problem is that the correct way of printing the variables passed to the template are using <?= ?> instead of <? ?> which works to execute code but not to print variables. [2]
Your “addFile” function is all right. Below is the code i've tested on my environment and I was able to upload an image successfully and print the url in the sheet.
Index.html:
<!DOCTYPE html>
<html>
<head>
<base target="_center">
<link rel="stylesheet" href="https://ssl.gstatic.com/docs/script/css/add-ons1.css">
<script src="https://code.jquery.com/jquery-3.4.1.js" integrity="sha256-WpOohJOqMqqyKL9FccASB9O0KwACQJpFTUBLTYOVvVU=" crossorigin="anonymous"></script>
</head>
<body>
<form id="myForm">
Please upload image below.<br /><br />
<input type="hidden" name="fname" id="fname" value="<?= fName ?>"/>
<input type="hidden" name="position" id="position" value="<?= position ?>"/>
<input type="file" name="file" id="file" accept="image/jpeg,.pdf" />
<input type="button" value="Submit" class="action" onclick="formData(this.parentNode)" />
<input type="button" value="Close" onclick="google.script.host.close()" />
</form>
<script>
//Disable the default submit action using “func1”
window.onload=func1;
function func1() {
document.getElementById('myForm').addEventListener('submit', function(event) {
event.preventDefault();
});
}
function formData(obj){
google.script.run.withSuccessHandler(closeIt).upload(obj);
}
function closeIt(e){
console.log(e);
google.script.host.close();
};
</script>
</body>
</html>
Code.gs (upload function):
function upload(obj) {
//Retrieve the input data of the Form object.
var newFileName = obj.fname;
var rowNum = obj.position;
var blob = obj.file;
var upFile = DriveApp.getFolderById('[folderid]').createFile(blob).setName(newFileName);
var fileUrl = upFile.getUrl();
var urlCell = SpreadsheetApp.getActiveSpreadsheet().getSheetByName('Sheet1').getRange(rowNum,5);
urlCell.setValue('=HYPERLINK("' + fileUrl + '","View image")');
}
[1] https://developers.google.com/apps-script/guides/html/communication
[2] https://developers.google.com/apps-script/guides/html/templates

How to get input information on web app like msg box using google script

I need output on web app which key information in input box. using html and java script I deployed as web app. once key the information I should get pop up msg on web app that information. Please help me out of this problem.
I have created HTML and javascript, using that data is getting capture in google spreadsheet but that information I should get on web app like pop up msg
Key information get in pop up msg in web app only
<!DOCTYPE html>
<html>
<head>
<base target="_top">
</head>
<body>
<h2>US P2P Standard Notes</h2>
<label>G-case #: </label><input type= "#" id="username">
<button id="btn">Pass</button> <form action="">
<p> </p>
</form>
<script>
document.getElementById("btn").addEventListener("click",doStuff);
function doStuff(){
var uname = document.getElementById("username").value;
google.script.run.userClicked(uname);
document.getElementById("username").value ="";
}
</script>
</body>
</html>
function doGet() {
return HtmlService.createHtmlOutputFromFile("page");
}
function userClicked(name){
var url = "docs.google.com/spreadsheets/d/…";
var ss = SpreadsheetApp.openByUrl(url);
var ws = ss.getSheetByName("Data");
ws.appendRow([name + "This is G-case#"]);
}
Try this:
I have it running as a dialog. I assume that you can take it from here and turn it into a Web App.
The html file was name aq4.html:
<html>
<head>
<base target="_top">
</head>
<body>
<h2>US P2P Standard Notes</h2>
<label>G-case #: </label><input type="text" id="username" />
<input type="button" id="btn" value="Pass" onClick="doStuff();" />
<script>
function doStuff(){
var uname=document.getElementById("username").value;
google.script.run
.withSuccessHandler(function(){
document.getElementById("username").value ="";
})
.userClicked(uname);
}
</script>
</body>
</html>
Since there was nothing in your form, I removed it. I also changed your button style to the input version. I added a withSuccessHandler to remove the entered text.
This is the google script:
function userClicked(name){
var ss=SpreadsheetApp.getActive();
var ws=ss.getSheetByName("Sheet1");
ws.appendRow([name + "This is G-case#"]);
return;
}
function showDialog() {
var userInterface=HtmlService.createHtmlOutputFromFile('aq4');
SpreadsheetApp.getUi().showModelessDialog(userInterface, "My Page")
}
Your saying something about a pop up but I haven't a clue as to what you're trying to say. Perhaps, you can elaborate on that a bit.
Oh and this is what the current dialog looks like:

Passing parameters from Dialog to server side script

I have a Google sheet template. Each time this is opened, I would like to open a Dialog to get two parameters and pass those parameters to a script bound to the Google sheet template. So far I have managed to define and open the Dialog. But the parameters don't show up in the server side script.
It seems like readFormData is not called when I push the "Create" button. If I replace readFormData with google.script.host.close(), the dialog box will close down. But not with readFormData. The same problem goes with close(). So my take on this is the Java script does not execute.
EDIT: I have solved the problem with a workaround. I replaced onclick="readFormData" with onclick="google.script.run.withSuccessHandler(google.script.host.close).getFormData(this.parentNode)" and then everything work as expected. (required a few changes on GS side as well) However, I can't figure out why I can't call my own javascript procedure readFormData(). With help form Chrome Developer Tool I can notice readFormData is not defined, raising an exception "Uncaught ReferenceError: readFormData is not defined". It fires every time i click on the button. So I guess it must be a syntax error that fools the parser or similar.
GS:
function getFormData(obj) {
Logger.log(obj);
return "hello";
}
function openDialog() {
var html = HtmlService.createHtmlOutputFromFile('index');
SpreadsheetApp.getUi() // Or DocumentApp or SlidesApp or FormApp.
.showModalDialog(html, 'Create file');
}
function onOpen(e) {
openDialog();
}
HTML:
<!DOCTYPE html>
<html>
<head>
<base target="_top">
<link rel="stylesheet"
href="https://ssl.gstatic.com/docs/script/css/add-ons1.css">
</head>
<body>
<form id="getSomeData">
<div class="inline form-group">
<label for="fname">Destination</label>
<input type="text" name="fname" style="width: 150px;">
</div>
<div class="inline form-group">
<label for="date">Date</label>
<input type="text" name="date" style="width: 40px;">
</div>
<div>
<input type="button" class = "action" value= "Create" onclick="readFormData()" >
</div>
</form>
<!-- <script src="//ajax.googleapis.com/ajax/libs/jquery/1.9.1/jquery.min.js"></script> -->
<script>
function success(msg) { // I have fixed the ((msg) error
alert(msg);
}
function readFormData(){
console.log("readFormData");
var form = document.getElementById("getSomeData").elements;
var obj ={};
for(var i = 0 ; i < form.length ; i++){
var item = form.item(i);
obj[item.name] = item.value;
}
google.script.run.withSuccessHandler(close).getFormData(obj);
}
function close(){
google.script.host.close();
}
</script>
</body>
</html>
It seems to me there is a misprint on "success" function which could lead to an interpretation problem :
success( ( msg).
Did you try without this "(" ?

Find Next in Google Apps

We have a bunch of documents we would like to convert to Google Docs. In MSWord we have a macro where our users hit a key command and it will automatically find a string of characters (%%%) and then select them. So we can quickly go in and replace all occurrences of them with the correct data.
I am unable to find anything in Google Docs or scripts that can do that.
TL;DR
I need to write a script that will find and select text so we can quickly write over it. Any help or thoughts?
This function works in conjunction with a sidebar to find and select text.
function findTextAndSelect(s){
var doc=DocumentApp.getActiveDocument();
var body=doc.getBody();
var rgel=body.findText(s);
if(rgel){
var rgbldr=doc.newRange();
rgbldr.addElement(rgel.getElement(),rgel.getStartOffset(),rgel.getEndOffsetInclusive());
var rg=rgbldr.build();
if(rg.getRangeElements().length>0){
doc.setSelection(rgbldr.build());
return 'found';
}
else{
return 'Not Found';
}
}else{
return 'Not Found';
}
}
**This is the sidebar code. **
<!DOCTYPE html>
<html>
<head>
<base target="_top">
<script src="//ajax.googleapis.com/ajax/libs/jquery/1.9.1/jquery.min.js"></script>
<script>
$(function() {
$('#txt1').val('');
});
function findAndSelect(){
$('#status').html('');
var txt=$('#txt1').val();
google.script.run
.withSuccessHandler(function(hl){
$('#status').html('<strong>Status:</strong>' + hl);
})
.findTextAndSelect(txt);
}
console.log("My code");
</script>
</head>
<body>
<br />Text:<br /><textarea id="txt1" rows="6" cols="35"></textarea>
<br /><input type="button" id="btn3" value="Find Text and Select" onClick="findAndSelect();" />
<div id="status"></div>
</body>
</html>
You need to add the code to load the sidebar and possibly put it into the menu.

How to Create a button for change page?

I have a form in a html file inside my google apps script project, I need to redirect to another html file when a submit button is Clicked.
HTML CODE:
<html>
<script>
function doSomething(){
alert('this one works too!');
//here Change of page
}
</script>
<body>
<h1 style="text-align:center;font-family:Tahoma;">HORAS LABORADAS<br/>
<form style="margin-left:90px;font-family:Trebuchet MS;">
<b>Nombre</b><br/>
<input type="button" onclick="doSomething()">
</form>
</body>
</html>
I call this by
function doGet() {
return HtmlService.createTemplateFromFile('prueba').evaluate();
}
HTML FILE1
<html>
<body>
<h1 style="text-align:center;font-family:Tahoma;">HORAS LABORADAS<br/>
<form style="margin-left:90px;font-family:Trebuchet MS;">
<b>Nombre</b><br/>
<?var url = getUrl();?><a href='<?=url?>?page=2'><input type='button' name='test' value='GO TO PAGE 2'></a>
</form>
</body>
</html>
HTML FILE2
<html>
<h1>This is Page 2.</h1><br/>
<?var url = getUrl();?><a href='<?=url?>?page=1'> <input type='button' name='test' value='RETURN TO PAGE 1'></a>
</html>
CODE.GS
function getUrl(){
var url = ScriptApp.getService().getUrl();
return url;
}
function doGet(requestInfo) {
var url = ScriptApp.getService().getUrl();
if (requestInfo.parameter && requestInfo.parameter['page'] == '2') {
return HtmlService.createTemplateFromFile('FILE2').evaluate();
}
return HtmlService.createTemplateFromFile('FILE1').evaluate();
}
If you simply want to redirect to another page, use the following:
<script>
function doSomething(){
alert('this one works too!');
window.location.href = "http://myurl.com";
}
</script>
Source: click this link