I have setup a Google Apps Script as a WebApp to take form data from an HTML form (non-google form) and insert the results into Google Sheets. Everything is working, but I am trying to get a custom landing page instead of the current Apps Script page, which is not useful for the end user.
I used this for reference: https://github.com/levinunnink/html-form-to-google-sheet
There is some info at the end of this GitHub guide, but it is not descriptive and I cannot find anything that works here or on GitHub. I know some JS, but I am no expert and could really use a hand figuring this out. Below is what I have and this is the closest I have gotten to everything working.
Here is my HTML.
<script>
function myFunction()
{ alert("The form was submitted successfully. Please press okay to continue...");
window.open("URL-to-thanks-page", "_top");
}
</script>
<form class="googleform" name="googleform" id="googleform" target="_top" method="POST" onsubmit="myFunction()" action="MY-GOOGLE-APPS-SCRIPTS-URL">
<!--FORM STUFF-->
<button type="submit" class="btn-default btn" name="submit" access="false" style="default" id="submit">Submit</button>
</form>
Here is my Code.gs
const sheetName = 'RSVP'
const scriptProp = PropertiesService.getScriptProperties()
function intialSetup () {
const activeSpreadsheet = SpreadsheetApp.getActiveSpreadsheet()
scriptProp.setProperty('key', activeSpreadsheet.getId())
}
function doPost (e) {
const lock = LockService.getScriptLock()
lock.tryLock(10000)
try {
const doc = SpreadsheetApp.openById(scriptProp.getProperty('key'))
const sheet = doc.getSheetByName(sheetName)
const headers = sheet.getRange(1, 1, 1, sheet.getLastColumn()).getValues()[0]
const nextRow = sheet.getLastRow() + 1
const newRow = headers.map(function(header) {
return header === 'Date' ? new Date() : e.parameter[header]
})
sheet.getRange(nextRow, 1, 1, newRow.length).setValues([newRow])
return ContentService
.createTextOutput(JSON.stringify({ 'result': 'success', 'row': nextRow }))
.setMimeType(ContentService.MimeType.JSON)
}
catch (e) {
return ContentService
.createTextOutput(JSON.stringify({ 'result': 'error', 'error': e }))
.setMimeType(ContentService.MimeType.JSON)
}
finally {
lock.releaseLock()
}
}
Any help would be greatly appreciated.
Respectfully,
I figured this out actually. I used the code on the original guide with a modification. In my HTML I removed the previous <script>
section and changed it to the following:
<script>
window.addEventListener("load", function() {
const form = document.getElementById('googleform');
form.addEventListener("submit", function(e) {
e.preventDefault();
const data = new FormData(form);
const action = e.target.action;
fetch(action, {
method: 'POST',
body: data,
})
.then(() => {
window.location.href = 'URL of thank you page';
})
});
});
</script>
This fixed the issue and now everything is working correctly.