Validation from submitting in Apps Script - google-apps-script

Please I need help. I have the same need of this post. I followed the instructions but I can't find my error. I'm frustratred.
When I submit with null fields, the script shows me a blank page.
When I submit with complete fields, the script shows me a blank page also and never upload the file.
This is my final code:
code.gs
function doGet(e) {
return HtmlService.createHtmlOutputFromFile('form.html');
}
function uploadFiles(form) {
try {
var dropbox = "NHD Papers";
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 + ", Division: " + form.myDivision + ", School: " + form.mySchool + ", State: " + form.myState);
return "<h2>File uploaded successfully!</h2><p>Copy and paste the following URL into registration:<br /><br /><strong>" + file.getUrl() + '</strong></p>';
} catch (error) {
return error.toString();
}
}
form.html
<p>
<form id="myForm" onsubmit="validateForm();">
<h1>NHD Paper Upload</h1>
<label>Name</label>
<input type="text" name="myName" class="required" placeholder="Enter your full name..">
<label>Division</label>
<input type="text" name="myDivision" class="required" placeholder="(ex. Junior or Senior)">
<label>School</label>
<input type="text" name="mySchool" class="required" placeholder="Enter your school..">
<label>Affiliate</label>
<input type="text" name="myAffiliate" class="required" placeholder="Enter your affiliate..">
<label>Select file to upload. </label>
<input type="file" name="myFile">
<input type="submit" value="Submit File" >
<br />
</form>
</p>
<div id="output"></div>
<script>
function validateForm() {
var x=document.getElementsByClassName('required');
for(var i = 0; i <x.length; i++){
if (x[i].value == null || x[i].value == "")
{
alert("All fields must be filled out.");
return false;
}
this.value='Please be patient while your paper is uploading..';
var myFormObject = document.getElementById('myForm');
google.script.run.withSuccessHandler(fileUploaded)
.uploadFiles(myFormObject);
}
}
function fileUploaded(status) {
document.getElementById('myForm').style.display = 'none';
document.getElementById('output').innerHTML = status;
}
</script>
<style>
input { display:block; margin: 15px; }
p {margin-left:20px;}
</style>
Regards,

In the IFRAME mode HTML forms are allowed to submit, but if the form has no action attribute it will submit to a blank page.
The solution suggested by the official documentation is to add the following JavaScript code to prevent all form submitions on load:
<script>
// Prevent forms from submitting.
function preventFormSubmit() {
var forms = document.querySelectorAll('form');
for (var i = 0; i < forms.length; i++) {
forms[i].addEventListener('submit', function(event) {
event.preventDefault();
});
}
}
window.addEventListener('load', preventFormSubmit);
</script>
You can also add a return false; or event.preventDefault() at the end of your validateForm() function.

Related

Script for selecting sheets using control

I have in a spreadsheet, a MENU with buttons linked to other sheets.
Since I have many sheets, I want that when selecting a button it is the same for a group of those sheets.
Ex: btn "Enter approved teachers", there are 4 sheets that are to enter that data, each one corresponds to a different area.
That when I click on this button, I skip a "popup" that shows me a list of that sheets and lets me select it with an "OK".
The part of selecting the sheet with a script is easy to do with a youtube tutorial, but the control of sheets and selection I can not find anywhere.
I haven't been able to try anything, as I don't have experience coding in Apps Script or Js.
Hopefully this is close to what you are looking for:
This a dialog I use for selecting which files I wish to backup from my spreadsheets.
html:
<!DOCTYPE html>
<html>
<head>
<base target="_top">
<style>
input {margin: 2px 5px 2px 0;}
#btn3,#btn4{display:none}
</style>
</head>
<body>
<form>
<input type="text" id="scr" name="script" size="60" placeholder="Enter Apps Script Id" onchange="getFileNames();" />
<br /><input type="text" id="fldr" name="folder" size="60" placeholder="Enter Backup Folder Id" />
<div id="shts"></div>
<br /><input type="button" value="0" onClick="unCheckAll();" size="15" id="btn3" />
<input type="button" value="1" onClick="checkAll();"size="15" id="btn4"/>
<br /><input type="checkbox" id="files" name="saveFiles" checked /><label for="files">Save Files</label>
<br /><input type="checkbox" id="json" name="saveJson" checked /><label for="json">Save JSON</label>
<br /><input type="button" value="Submit" onClick="backupFiles();" />
</form>
<script>
function getFileNames() {
const scriptid = document.getElementById("scr").value;
google.script.run
.withSuccessHandler((names) => {
document.getElementById('btn3').style.display = "inline";
document.getElementById('btn4').style.display = "inline";
names.forEach((name,i) => {
let br = document.createElement("br");
let cb = document.createElement("input");
cb.type = "checkbox";
cb.id = `cb${i}`;
cb.name = `cb${i}`;
cb.className = "cbx";
cb.value = `${name}`;
cb.checked = true;
let lbl = document.createElement("label");
lbl.htmlFor = `cb${i}`;
lbl.appendChild(document.createTextNode(`${name}`));
document.getElementById("shts").appendChild(cb);
document.getElementById("shts").appendChild(lbl);
document.getElementById("shts").appendChild(br);
});
})
.getAllFileNames({scriptId:scriptid});
}
function unCheckAll() {
let btns = document.getElementsByClassName("cbx");
console.log(btns.length);
for(let i =0;i<btns.length;i++) {
btns[i].checked = false;
}
}
function checkAll() {
let btns = document.getElementsByClassName("cbx");
console.log(btns.length)
for(let i = 0;i<btns.length;i++) {
btns[i].checked = true;
}
}
function backupFiles() {
console.log('backupFiles');
sObj = {};
sObj.script = document.getElementById('scr').value;
sObj.folder = document.getElementById('fldr').value;
sObj.saveJson = document.getElementById('json').checked?'on':'';
sObj.saveFiles = document.getElementById('files').checked?'on':'';
sObj.selected = [];
console.log("1");
const cbs = document.getElementsByClassName("cbx");
let selected = [];
for(let i = 0;i<cbs.length; i++) {
let cb = cbs[i];
if(cb.checked) {
sObj.selected.push(cb.value)
}
}
console.log("2");
google.script.run
.withSuccessHandler(function(obj){google.script.host.close();})
.scriptFilesBackup(sObj);
console.log(JSON.stringify(sObj));
}
</script>
</body>
</html>
This is what the dialog looks like:

Google Apps Script is corrupting/blanking-out all files uploaded through a form I created. How do I fix this?

I have used a Google Apps Script form to upload receipts into Google Drive for a couple of years without problems. A few months ago, files have started to come across as completely blank or corrupted. While a file will appear in Drive, I can't open it or, if it's a PDF, it's the same number of pages but completely blank. Only text files seem to work.
I understand conceptually that I need to add a function to allow the script to process the file on the front end and then pass it to the server (based on this and this). But I can't seem to get the script right because my structure is sufficiently different that it confuses me, frankly.
Here is my form.html:
<!doctype html>
<form id="myForm" align="left">
Your first name: <input type="text" name="myName"><br><br>
<input type="file" name="myFile1"><input type="text" name="myReceipt1" placeholder="Vendor (who was paid)...">
<input type="text" name="myProgram1" placeholder="GenOps, OWP, VSP, etc."><br>
<input type="text" name="myDesc1" placeholder="Expense Desc (e.g. catering, airfare, etc.)" style="width:300px;"><br>
<input type="date" name="myDate1" placeholder="Date Charged (yyyy.mm.dd)" style="width:200px;">
<input type="text" name="myAmt1" placeholder="Amount (dd.cc)"><br>
<input type="file" name="myFile2"><input type="text" name="myReceipt2" placeholder="Vendor (who was paid)...">
<input type="text" name="myProgram2" placeholder="GenOps, OWP, VSP, etc."><br>
<input type="text" name="myDesc2" placeholder="Expense Desc (e.g. catering, airfare, etc.)" style="width:300px;"><br>
<input type="date" name="myDate2" placeholder="Date Charged (yyyy.mm.dd)" style="width:200px;">
<input type="text" name="myAmt2" placeholder="Amount (dd.cc)"><br>
<input type="submit" value="Upload File(s)" style="background-color:#ffd382"
onclick="this.value='Uploading...';
google.script.run.withSuccessHandler(fileUploaded)
.uploadFiles(this.parentNode);
return false;">
</form>
<script>
function fileUploaded(status) {
document.getElementById('myForm').style.display = 'none';
document.getElementById('output').innerHTML = status;
}
</script>
Here is my server.gs:
function doGet(e) {
return HtmlService.createTemplateFromFile('form.html')
.evaluate() // evaluate MUST come before setting the Sandbox mode
.setXFrameOptionsMode(HtmlService.XFrameOptionsMode.ALLOWALL)
.setTitle("AmEx Receipt Upload");8
}
function uploadFiles(form) {
try {
var dropbox = "Receipts"; //name of Drive folder to save uploaded files
var folder, folders = DriveApp.getFoldersByName(dropbox);
if (folders.hasNext()) {
folder = folders.next();
} else {
folder = DriveApp.createFolder(dropbox);
}
var blob = form.myFile1;
var file = folder.createFile(blob);
file.setDescription("Uploaded by " + form.myName);
file.setName(form.myDate1 + "_" + form.myReceipt1 + "_" + form.myProgram1 + "_" + form.myDesc1 + " - " + form.myAmt1);
var blob = form.myFile2;
var file = folder.createFile(blob);
file.setDescription("Uploaded by " + form.myName);
file.setName(form.myDate2 + "_" + form.myReceipt2 + "_" + form.myProgram2 + "_" + form.myDesc2 + " - " + form.myAmt2);
return "Your receipts have been uploaded. Refresh the page if you have more to upload.";
} catch (error) {
return error.toString();
}
}
Any help you can render would be greatly appreciated. It seems that every adjustment I make only makes things worse. If you need me to simply the code snippets more than I have, I certainly can.
Thank you in advance!
Modification points:
I thought that the issue that the uploaded files are broken might be the same issue with this thread.
In order to avoid to break the uploaded file, for example, it is required to convert the file to the byte array and base64, and then, sent to Google Apps Script.
But when I saw your script, I thought that in order to use above, it is required to send 2 files and several values, and requierd to modify both Javascript and Google Apps Script. I thought that this might be a bit complicated. So I proposed the modified script as an answer.
Modified script:
In this modification, the file is converted to the byte array and sent to Google Apps Script.
HTML&Javascript side:
<form id="myForm" align="left">
Your first name: <input type="text" name="myName"><br><br>
<input type="file" name="myFile1">
<input type="text" name="myReceipt1" placeholder="Vendor (who was paid)...">
<input type="text" name="myProgram1" placeholder="GenOps, OWP, VSP, etc."><br>
<input type="text" name="myDesc1" placeholder="Expense Desc (e.g. catering, airfare, etc.)" style="width:300px;"><br>
<input type="date" name="myDate1" placeholder="Date Charged (yyyy.mm.dd)" style="width:200px;">
<input type="text" name="myAmt1" placeholder="Amount (dd.cc)"><br>
<input type="file" name="myFile2">
<input type="text" name="myReceipt2" placeholder="Vendor (who was paid)...">
<input type="text" name="myProgram2" placeholder="GenOps, OWP, VSP, etc."><br>
<input type="text" name="myDesc2" placeholder="Expense Desc (e.g. catering, airfare, etc.)" style="width:300px;"><br>
<input type="date" name="myDate2" placeholder="Date Charged (yyyy.mm.dd)" style="width:200px;">
<input type="text" name="myAmt2" placeholder="Amount (dd.cc)"><br>
<input type="submit" value="Upload File(s)" style="background-color:#ffd382" onclick="submitValues(this);return false;">
</form>
<div id = "output"></div>
<script>
function submitValues(e) {
e.value = 'Uploading...';
const files = [e.parentNode.myFile1.files[0], e.parentNode.myFile2.files[0]];
const object = [...e.parentNode].reduce((o, obj) => Object.assign(o, {[obj.name]: obj.value}), {});
if (files.some(f => f)) {
Promise.all(
files.map(file => new Promise((resolve, reject) => {
if (file) {
const fr = new FileReader();
fr.onload = f => resolve({filename: file.name, mimeType: file.type, bytes: [...new Int8Array(f.target.result)]});
fr.onerror = err => reject(err);
fr.readAsArrayBuffer(file);
} else {
resolve({});
}
}))
).then(ar => {
[object.myFile1, object.myFile2] = ar;
google.script.run.withSuccessHandler(fileUploaded).uploadFiles(object);
});
}
}
function fileUploaded(status) {
document.getElementById('myForm').style.display = 'none';
document.getElementById('output').innerHTML = status;
}
</script>
Google Apps Script side:
In this case, uploadFiles is modified.
function uploadFiles(form) {
try {
var dropbox = "Receipts"; //name of Drive folder to save uploaded files
var folder, folders = DriveApp.getFoldersByName(dropbox);
if (folders.hasNext()) {
folder = folders.next();
} else {
folder = DriveApp.createFolder(dropbox);
}
// --- I modified below script.
var file1 = form.myFile1;
if (Object.keys(file1).length > 0) {
var blob = Utilities.newBlob(file1.bytes, file1.mimeType, file1.filename); // Modified
var file = folder.createFile(blob);
file.setDescription("Uploaded by " + form.myName);
file.setName(form.myDate1 + "_" + form.myReceipt1 + "_" + form.myProgram1 + "_" + form.myDesc1 + " - " + form.myAmt1);
}
var file2 = form.myFile2;
if (Object.keys(file2).length > 0) {
var blob = Utilities.newBlob(file2.bytes, file2.mimeType, file2.filename); // Modified
var file = folder.createFile(blob);
file.setDescription("Uploaded by " + form.myName);
file.setName(form.myDate2 + "_" + form.myReceipt2 + "_" + form.myProgram2 + "_" + form.myDesc2 + " - " + form.myAmt2);
}
// ---
return "Your receipts have been uploaded. Refresh the page if you have more to upload.";
} catch (error) {
return error.toString();
}
}
Note:
In this case, the maximum file size is less than 50 MB because the blob is used at Google Apps Script. Please be careful this.
In my environment, I could confirm that the proposed script worked. But if the script doesn't work in your environment, can you provide the script for replicating the issue? By this, I would like to confirm it.
References:
FileReader
Promise.all()
newBlob(data, contentType, name)

Google App Script to Upload File from Website to Google Drive - works for text file but not binary

I need to upload files to my Google Drive via a Google App Script. The goal is to be able to let users upload a file to my Google Drive from my website. The code is largely the same as a tutorial I found online, I just added a link to my website banner and also added some code to send me an email when someone uploads a file.
The problem is, it works for text file but not binary files (jpeg, pdf, etc). It correctly creates a file in the appropriate folder, but the file cannot be opened. The binary file that gets created does have some data in it.. when I open the created file in TextEdit, it does look somewhat similar to the original, but some of the characters look different. The filesize of the new created file is also larger than the original.
The problem does not occur with text files. The code is listed below.
HTML code
<!doctype html>
<style type="text/css">
body {
background-color: #FFFFFF;
}
</style>
<BR>
<BR>
<BR>
<div align="center">
<p><img src="https://rosspalmermd.files.wordpress.com/2020/05/color-logo-with-background.png" width=320></p>
<table width="459" border="0">
<tbody>
<tr>
<td width="462"><div align="center">
<hr>
</div>
<form id="myForm" align="center">
<input type="text" name="myName" placeholder="Your name...">
<input type="email" name="myEmail" placeholder="Your email...">
<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>
<hr></td>
</tr>
</tbody>
</table>
<h3> </h3>
<p> </p>
</div>
Server side code:
function doGet(e) {
return HtmlService.createHtmlOutputFromFile('form.html');
}
function uploadFiles(form) {
try {
var dropbox = "DriveUploader";
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);
MailApp.sendEmail("email#email.com",
"File uploaded to website",
form.myName + " (" + form.myEmail + ") has uploaded a file " + file.getUrl());
return "File uploaded successfully. We will contact you soon.";
} catch (error) {
return error.toString();
}
}
I found the solution for your problem, here is the code:
HTML code:
<!DOCTYPE html>
<style type="text/css">
body {
background-color: #FFFFFF;
}
</style>
<BR>
<BR>
<BR>
<div align="center">
<p><img src="https://rosspalmermd.files.wordpress.com/2020/05/color-logo-with-background.png" width=320></p>
<table width="459" border="0">
<tbody>
<tr>
<td width="462"><div align="center">
<hr>
</div>
<form id="myForm" align="center">
<div id="data"></div>
<input type="text" id="myName" name="myName" placeholder="Your name...">
<input type="email" id="myEmail" name="myEmail" placeholder="Your email...">
<input id="uploadfile" type="file" name="myFile">
<input type="submit" value="Upload File"
onclick="this.value='Uploading..';
getFiles();
return false;">
</form>
<div id="output"></div>
<script>
function getFiles() {
const name = document.getElementById('myName').value;
const email = document.getElementById('myEmail').value;
const f = document.getElementById('uploadfile');
[...f.files].forEach((file, i) => {
const fr = new FileReader();
fr.onload = (e) => {
const data = e.target.result.split(",");
const obj = {fileName: f.files[i].name, mimeType: data[0].match(/:(\w.+);/)[1], data: data[1],myName: name,myEmail: email};
google.script.run.withSuccessHandler(fileUploaded)
.uploadFiles(obj);
}
fr.readAsDataURL(file);
});
}
function fileUploaded(status) {
document.getElementById('myForm').style.display = 'none';
document.getElementById('output').innerHTML = status;
}
</script>
<style>
input { display:block; margin: 20px; }
</style>
<hr></td>
</tr>
</tbody>
</table>
<h3> </h3>
<p> </p>
</div>
Server side code:
function doGet(e) {
return HtmlService.createHtmlOutputFromFile('form.html');
}
function uploadFiles(obj) {
try {
var dropbox = "DriveUploader";
var folder, folders = DriveApp.getFoldersByName(dropbox);
if (folders.hasNext()) {
folder = folders.next();
} else {
folder = DriveApp.createFolder(dropbox);
}
var blob = Utilities.newBlob(Utilities.base64Decode(obj.data), obj.mimeType, obj.fileName);
var file = folder.createFile(blob);
file.setDescription("Uploaded by " + obj.myName);
MailApp.sendEmail("email#email.com",
"File uploaded to website",
obj.myName + " (" + obj.myEmail + ") has uploaded a file " + file.getUrl());
return "File uploaded successfully. We will contact you soon.";
} catch (error) {
return error.toString();
}
}

Saving information in google sheets from my form

I try to save file on google drive and information in google sheets. But information in Sheets comes like Java.object.
Here is how it looks like in Code.gs :
var FOLDER_ID = '1jxBwrsz0JdBHcADpUUMespe';
var SHEET_ID = '1oJcKQ2RrtxxE1mn_CP-UAHefDxV7zg4';
function doPost(e) {
var data = Utilities.base64Decode(e.parameters.data);
var blob = Utilities.newBlob(data, e.parameters.mimetype, e.parameters.name);
var folder = DriveApp.getFolderById(FOLDER_ID);
var file = folder.createFile(blob);
folder.createFolder(name)
var res = [];
SpreadsheetApp.openById(SHEET_ID).getSheets()[0].appendRow([e.parameters.name, file.getUrl()].concat(res));
return ContentService.createTextOutput("Done.")
}
Here is how it looks like in the HTML file :
<form action="https://script.google.com/macros/s/AKfycbxkzg6ud1VyTI2W4gs-CRJRS3i3qLDXQIGevtyy/exec" id="form" method="post">
<div id="data"></div>
<div class="form-group">
<label for="name">Имя</label>
<input type="text" id='name' name="name" placeholder="Имя" />
</div>
<div class="form-group">
<label for="comment">Комм</label>
<input type="text" name="comment" placeholder="Комментарий" />
</div>
<input name="file" id="uploadfile" type="file">
<input id="submit" type="submit">
</form>
<script>
$('#uploadfile').on("change", function() {
var file = this.files[0];
var fr = new FileReader();
var name = $('#name').value;
fr.fileName = file.name
fr.onload = function(e) {
e.target.result
html = '<input type="hidden" name="data" value="' + e.target.result.replace(/^.*,/, '') + '" >';
html += '<input type="hidden" name="mimetype" value="' + e.target.result.match(/^.*(?=;)/)[0] + '" >';
html += '<input type="hidden" name="filename" value="' + e.target.fileName + '" >';
html += '<input type="hidden" name="name" value="' + name + '" >';
$("#data").empty().append(html);
}
fr.readAsDataURL(file);
});
</script>
Result in Google sheet
How to get data in a readable format?
Personally, I never use forms. Here's an examples that creates 5 text boxes. Validates that you put something into them and returns the code to the server via google.script.run for further processing (i.e. Logger.log the data). I create the html server side and loaded it on the on DOM ready event with JQuery.
Codes.gs
function buildForm(){
var s='';
for(var i=0;i<5;i++){
s+=Utilities.formatString('<br /><input class="jim" type="text" value="" id="%s" />%s',"txt" + i,"text" + Number(i+1));
}
s+='<br /><input type="button" value="Submit" onClick="getValues();" /><input type="button" value="Close" onClick="google.script.host.close();" />';
return s;
}
function saveValues(A){
for(var i=0;i<A.length;i++){
Logger.log('\nid=%s\nvalue=%s',A[i].id,A[i].value);
}
}
function showFormDialog(){
var ui=HtmlService.createHtmlOutputFromFile('form')
SpreadsheetApp.getUi().showModelessDialog(ui,'My Form');
}
form.html:
<!DOCTYPE html>
<html>
<head>
<base target="_top">
<script src="//ajax.googleapis.com/ajax/libs/jquery/1.9.1/jquery.min.js"></script>
<script>
$(function(){
google.script.run
.withSuccessHandler(function(html){$('#form').html(html);})
.buildForm();
});
function getValues(){
var elements=document.getElementsByClassName('jim');
var el=[];
console.log('elements.length=%s',elements.length);
for(var i=0;i<elements.length;i++){
var obj={};
obj['id']='txt' + i;
obj['value']=$('#' + 'txt' + i).val();
el.push(obj);
}
var dataValid=true;
for(var i=0;i<el.length;i++){
console.log('id=%s, value=%s',el[i].id, el[i].value);
if(!el[i].value){
dataValid=false;
$('#'+el[i].id).css('background','#ffff00');
}else{
$('#'+el[i].id).css('background','#ffffff');
}
}
if(dataValid){
google.script.run.saveValues(el);
}else{
alert('Invalid Data Found...Try again sucker....');
}
}
console.log('MyCode');
</script>
<style>
input {margin:5px 5px 0 0;}
</style>
</head>
<body>
<div id="form"></div>
</body>
</html>

Google Scripts HtmlService returns undefined form data

I am trying to create a web app whereby a user fills out a form and the data gets populated into a google sheet. My problem is after I fill out the form the sheet gets populated with undefined data.
How do I define this data and append to a new row each time I fill out the form.
Example was taken from here.
Code.gs
function doGet(e){
return handleResponse(e);
}
var SHEET_NAME = "Sheet1";
var SCRIPT_PROP = PropertiesService.getScriptProperties(); // new property service
function handleResponse(e) {
var lock = LockService.getPublicLock();
lock.waitLock(30000); // wait 30 seconds before conceding defeat.
try {
var doc = SpreadsheetApp.openById(SCRIPT_PROP.getProperty("key"));
var sheet = doc.getSheetByName(SHEET_NAME);
var headRow = e.parameter.header_row || 1;
var headers = sheet.getRange(1, 1, 1, sheet.getLastColumn()).getValues()[0];
var nextRow = sheet.getLastRow()+1; // get next row
var row = [];
// loop through the header columns
for (i in headers){
if (headers[i] == "Timestamp"){ // special case if you include a 'Timestamp' column
row.push(new Date());
} else { // else use header name to get data
row.push(e.parameter[headers[i]]);
}
}
// more efficient to set values as [][] array than individually
sheet.getRange(nextRow, 1, 1, row.length).setValues([row]);
// return json success results
return HtmlService.createHtmlOutputFromFile('index');
} catch(e){
// if error return this
return ContentService
.createTextOutput(JSON.stringify({"result":"error", "error": e}))
.setMimeType(ContentService.MimeType.JSON);
} finally { //release lock
lock.releaseLock();
}
}
function setup() {
var doc = SpreadsheetApp.getActiveSpreadsheet();
SCRIPT_PROP.setProperty("key", doc.getId());
}
index.html
<!DOCTYPE html>
<html>
<head>
<base target="_top">
<script>
var $form = $('form#test'),
url = 'https://...';
$('#submit-form').on('click', function(e) {
e.preventDefault();
var jqxhr = $.ajax({
url: url,
method: "GET",
dataType: "json",
data: $form.serializeObject()
}).success(
// do something
);
})
</script>
</head>
<body>
<form id="test">
<p><label>ID</label>
<input type="number" name="ID"/></p>
<p><label>Part Number</label>
<input type="text" name="Part Number"/></p>
<p><label>Description</label>
<input type="text" name="Description"/></p>
<p><label>Item Link</label>
<input type="url" name="Item Link"/></p>
<p><label>Supplier</label>
<input type="text" name="Supplier"/></p>
<p><label>Manufacturer</label>
<input type="text" name="Manufacturer"/></p>
<p><label>Pins</label>
<input type="number" name="Pins"/></p>
<p><label>Size</label>
<input type="text" name="Size"/></p>
<p><label>Order Number</label>
<input type="number" name="Order Number"/></p>
<p><label>Location</label>
<input type="text" name="Location"/></p>
<p><input type="submit" value="submit-form"/></p>
</form>
</body>
</html>
Since you've borrowed code from another site it seems overly complicated for my taste. Here is a simpler solution IMHO. I don't see parameter e used anywhere so i removed. Also the use of html form is not needed but I left it as is
Code.gs
function doGet(){
try {
return HtmlService.createHtmlOutputFromFile("HTML_Test");
}
catch(err) {
return ContentService
.createTextOutput(JSON.stringify({"result":"error", "error": err}))
.setMimeType(ContentService.MimeType.JSON);
}
}
function submitData(data) {
var shid = "your spreadsheet id here";
var ss = SpreadsheetApp.openById(shid);
var sh = ss.getSheetByName("Sheet1");
try {
sh.getRange(sh.getLastRow()+1,1,1,data.length).setValues([data]);
return "success"
}
catch(err) {
sh.getRange(sh.getLastRow()+1,1).setValue(err);
return err;
}
}
HTML_Test.html
<!DOCTYPE html>
<html>
<head>
<base target="_top">
</head>
<body>
<form id="test">
<p><label>ID</label>
<input type="number" id="ID"/></p>
<p><label>Part Number</label>
<input type="text" id="Part Number"/></p>
<p><label>Description</label>
<input type="text" id="Description"/></p>
<p><label>Item Link</label>
<input type="url" id="Item Link"/></p>
<p><label>Supplier</label>
<input type="text" id="Supplier"/></p>
<p><label>Manufacturer</label>
<input type="text" id="Manufacturer"/></p>
<p><label>Pins</label>
<input type="number" id="Pins"/></p>
<p><label>Size</label>
<input type="text" id="Size"/></p>
<p><label>Order Number</label>
<input type="number" id="Order Number"/></p>
<p><label>Location</label>
<input type="text" id="Location"/></p>
<p><input type="button" value="Submit" onclick="submitForm()"/></p>
</form>
<script>
function submitForm() {
try {
var data = [];
data.push(document.getElementById("ID").value);
data.push(document.getElementById("Part Number").value);
data.push(document.getElementById("Description").value);
data.push(document.getElementById("Item Link").value);
data.push(document.getElementById("Supplier").value);
data.push(document.getElementById("Manufacturer").value);
data.push(document.getElementById("Pins").value);
data.push(document.getElementById("Size").value);
data.push(document.getElementById("Order Number").value);
data.push(document.getElementById("Location").value);
google.script.run.withSuccessHandler(success).submitData(data);
}
catch(err) {
alert(err);
}
}
function success(msg) {
alert(msg);
}
</script>
</body>
</html>