Skip to content

Instantly share code, notes, and snippets.

@patheticGeek
Last active February 27, 2022 18:16
Show Gist options
  • Save patheticGeek/9444a224dbc91dfca0a9ffecc2dd40ef to your computer and use it in GitHub Desktop.
Save patheticGeek/9444a224dbc91dfca0a9ffecc2dd40ef to your computer and use it in GitHub Desktop.
Use google sheet as a contact form
// original from: http://mashe.hawksey.info/2014/07/google-sheets-as-a-database-insert-with-apps-script-using-postget-methods-with-ajax-example/
// original gist: https://gist.github.com/willpatera/ee41ae374d3c9839c2d6
function doGet(e){
return handleResponse(e);
}
// Enter sheet name where data is to be written below
var SHEET_NAME = "Sheet1";
var SCRIPT_PROP = PropertiesService.getScriptProperties(); // new property service
function handleResponse(e) {
// shortly after my original solution Google announced the LockService[1]
// this prevents concurrent access overwritting data
// [1] http://googleappsdeveloper.blogspot.co.uk/2011/10/concurrency-and-google-apps-script.html
// we want a public lock, one that locks for all invocations
var lock = LockService.getPublicLock();
lock.waitLock(30000); // wait 30 seconds before conceding defeat.
try {
// next set where we write the data - you could write to multiple/alternate destinations
var doc = SpreadsheetApp.openById(SCRIPT_PROP.getProperty("key"));
var sheet = doc.getSheetByName(SHEET_NAME);
var message = "Name: " + e.parameter['Name'] + "Email: " + e.parameter['Email'] + " \nMessage: \n" + e.parameter['Message'];
var subject = "Contacted by " + e.parameter['Name'];
MailApp.sendEmail('youremail@example.com', e.parameter['Email'], subject, message);
// we'll assume header is in row 1 but you can override with header_row in GET/POST data
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 ContentService
.createTextOutput(JSON.stringify({"result":"success", "row": nextRow}))
.setMimeType(ContentService.MimeType.JSON);
} 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());
}
const CONTACT_FORM_URL = "https://script.google.com/macros/s/YOUR_ID/exec";
async function formSubmit(e) {
if (e) e.preventDefault();
const submitBtn = document.getElementById("submitBtn");
const nameInput = document.getElementById("nameInput");
const emailInput = document.getElementById("emailInput");
const messageInput = document.getElementById("messageInput");
const numberInput = document.getElementById("numberInput");
submitBtn.setAttribute("disabled", "true");
submitBtn.innerText = "Submitting..";
const params = new URLSearchParams({
name: nameInput.value,
email: emailInput.value,
message: messageInput.value,
phone: numberInput.value,
});
const request = await fetch(`${CONTACT_FORM_URL}?${params.toString()}`);
const response = await request.json();
submitBtn.innerText = "Thanks for contacting us"
}
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta http-equiv="X-UA-Compatible" content="IE=edge">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Sheet Form</title>
</head>
<body>
<form id="form">
<input type="text" id="nameInput" placeholder="nameInput" />
<input type="email" id="emailInput" placeholder="emailInput" />
<input type="number" id="numberInput" placeholder="numberInput" />
<textarea type="text" id="messageInput" placeholder="messageInput" ></textarea>
<button id="submitBtn" type="submit">Submit</button>
</form>
<script>
const CONTACT_FORM_URL = "https://script.google.com/macros/s/YOUR_ID/exec";
async function formSubmit(e) {
if (e) e.preventDefault();
const submitBtn = document.getElementById("submitBtn");
const nameInput = document.getElementById("nameInput");
const emailInput = document.getElementById("emailInput");
const messageInput = document.getElementById("messageInput");
const numberInput = document.getElementById("numberInput");
submitBtn.setAttribute("disabled", "true");
submitBtn.innerText = "Submitting..";
const params = new URLSearchParams({
name: nameInput.value,
email: emailInput.value,
message: messageInput.value,
phone: numberInput.value,
});
const request = await fetch(`${CONTACT_FORM_URL}?${params.toString()}`);
const response = await request.json();
submitBtn.innerText = "Thanks for contacting us"
}
document.getElementById("formSubmit").addEventListener('submit', formSubmit);
</script>
</body>
</html>
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment