How to submit HTML form to Google Sheet
In six simple steps, you can submit HTML form to google sheets.1. Create a new Google Sheet
- First, go to Google Sheets and with
Start a new spreadsheet
the templateBlank
. - Rename it. With any name you want.
- Put the following headers into the first row:
A | B | C | ... | |
---|---|---|---|---|
1 | timestamp | firstName |
2. Create a Google Apps Script
- Click on
Tools > Script Editor…
which should open a new tab. - Rename it
Submit Form to Google Sheets
. Sometimes the name takes time, wait for that until you are 100% satisfied - When you are done with Tools->Script Editor and renaming, then, delete the
function myFunction() {}
block within theCode.gs
tab. - Paste the following script in it's place and
File > Save
:
var sheetName = 'Sheet1'
var scriptProp = PropertiesService.getScriptProperties()
function intialSetup () {
var activeSpreadsheet = SpreadsheetApp.getActiveSpreadsheet()
scriptProp.setProperty('key', activeSpreadsheet.getId())
}
function doPost (e) {
var lock = LockService.getScriptLock()
lock.tryLock(10000)
try {
var doc = SpreadsheetApp.openById(scriptProp.getProperty('key'))
var sheet = doc.getSheetByName(sheetName)
var headers = sheet.getRange(1, 1, 1, sheet.getLastColumn()).getValues()[0]
var nextRow = sheet.getLastRow() + 1
var newRow = headers.map(function(header) {
return header === 'timestamp' ? 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()
}
}
Now you created a Sheet -> This sheet is already saved with some one of your choice -> and from Tools>Scripts Editor the script is past. Done now you can move the next step.
3. Run the setup function
- Next, go to
Run > setup
to run this function. - In the
Authorization Required
dialog, click onReview Permissions
. - Sign in or pick the Google account associated with this projects.
- You should see a dialog that says
Hi {Your Name}
,Submit Form to Google Sheets wants to
... - Click
Allow
4. Add a new project trigger
- Click on
Edit > Current project’s triggers
. - In the dialog click
No triggers set up. Click here to add one now.
- In the dropdowns select
doPost
- Set the events fields to
From spreadsheet
andOn form submit
- Then click
Save
5. Publish the project as a web app
- Click on
Publish > Deploy as web app…
. - Set
Project Version
toNew
and putinitial version
in the input field below. - Leave
Execute the app as:
set toMe(your@address.com)
. - For
Who has access to the app:
selectAnyone, even anonymous
. - Click
Deploy
. - In the popup, copy the
Current web app URL
from the dialog. - And click
OK
.
IMPORTANT! If you have a custom domain with Gmail, you might need to clickOK
, refresh the page, and then go toPublish > Deploy as web app…
again to get the proper web app URL. It should look something likehttps://script.google.com/a/yourdomain.com/macros/s/XXXX…
.
6. Input your web app URL
Open the file named.
NOTE: In the above code you can see that <SCRIPT URL> you will replace it with your URL.index.html
Online 12 replace <SCRIPT URL>
with your script URL: <form name="contact">
<input name="email" type="email" placeholder="Email" required>
<button type="submit">Send</button>
</form>
<script>
const scriptURL = '<SCRIPT URL>'
const form = document.forms['contact']
form.addEventListener('submit', e => {
e.preventDefault()
fetch(scriptURL, { method: 'POST', body: new FormData(form)})
.then(response => console.log('Success!', response))
.catch(error => console.error('Error!', error.message))
})
</script>
7. Adding additional form data
To capture additional data, you'll just need to create new columns with titles matching exactly the
name
values from your form inputs. For example, if you want to add first and last name inputs, you'd give them name
values like so: <form name="submit-to-google-sheet">
<input name="email" type="email" placeholder="Email" required>
<input name="firstName" type="text" placeholder="First Name">
<input name="lastName" type="text" placeholder="Last Name">
<button type="submit">Send</button>
</form>
Then create new headers with the exact, case-sensitive
name
values:A | B | C | D | ... | |
---|---|---|---|---|---|
1 | timestamp | firstName | lastName |
thank you, really helpful
ReplyDeleteI run this from localhost, and it the sheet i get undefined variables, did i do anything wrong?
ReplyDeleteokay i needed to replace name attribute with the exact name in the sheet.
ReplyDeleteSee, the Google marketing listing process always occurs in function of a search request for specific words. Imagine that you are into furniture retail sales.https://edkentmedia.com/ppc-management-toronto/
ReplyDeletethanks man, its working fine for me
ReplyDeleteDig this. Using drive api, it can accept images too. Got it working with files.
ReplyDeletehow to submit multiple values like from checkbox
ReplyDeleteyou need to add this to array.
DeleteIs there a Youtube tutorial for this ? Thanks
ReplyDeletethis is not work...help me
ReplyDeleteThank You..so much.. i am happy..for this code
ReplyDeleteNo its Not Working
ReplyDeletethis code again not working.....what am i do now?
ReplyDeleteThis is amazing! Thanks so much
ReplyDeleteWhat about TWO forms on the same page? This script doesn't support it. What changes need to be made and how can I have two identical forms with different form names post to the same sheet? All the input fields are identical. One form is in the footer area and the other form is a modal accessible through button clicks throughout the page for convenience. and THANK YOU everything else works!!
ReplyDeleteYou forgot to mention you have to specify the form name in the html java script
AND
I had to add a doGet() function to avoid a bunch of errors.
Thanks
shawn@dontpop.com is my email thanks
DeleteWhile adding new project trigger, under "Choose which function to run", there are only 'doGet', 'handleResponse' and 'setup' options.
ReplyDeleteThere isn't a 'doPost' option at all.
What is to be done? Proceed with 'doGet'?
Please revert ASAP.
ReplyDeleteUncaught TypeError: Cannot read property 'addEventListener' of undefined
I think I've done everything fine. But when I press submit I get this error and it opens again the form on a new tab with the url from my website plus the text written on the inputs.
It seems there si something wrong with submit. Am I right?
Thank you anyway.
Well thi issue is solved. Had another name on the tag form :)
DeleteAnyway now it seems I've having problem with CORS:
ailed to load https://script.google.com/macros/s/.../exec: No 'Access-Control-Allow-Origin' header is present on the requested resource. Origin 'https://MYDOMAIN.com' is therefore not allowed access. If an opaque response serves your needs, set the request's mode to 'no-cors' to fetch the resource with CORS disabled.
and de Failed fetch:
fetch.then.catch.error @
Promise.catch (async)
form.addEventListener.e @
I've searched and found in another post about the same thing. send post data into google spreadsheet. And this is what I found about CORS:
CORS Issues
If you’re seeing an error like the following: “No ‘Access-Control-Allow-Origin’ header is present on the requested resource,” double-check you’re making a GET request and not a POST request.
I've set like this code with POST and doPost.
So I don't know what can be wrong....
I respect this article for the very much investigated substance and magnificent wording. I got so included in this material that I couldn't quit perusing. I am awed with your work and aptitude. Much obliged to you to such an extent. vpn
ReplyDeleteGood website! I truly love how it is easy on my eyes it is. I am wondering how I might be notified whenever a new post has been made. I have subscribed to your RSS which may do the trick? Have a great day! https://internetprivatsphare.de/bundesliga-stream-mit-vpn/
ReplyDeleteThat appears to be excellent however i am still not too sure that I like it. At any rate will look far more into it and decide personally! die besten vpn
ReplyDeleteBut nowadays this technique is not enough for a representation of contemporary web pages high-loaded with content and media. coding image example
ReplyDeleteIn Facebook, we can share stories of people who use your product or service. If they give you great feedback, share it! It’ll spread the message that your product is effective enough for someone to give you positive feedback. Effective Facebook Marketing
ReplyDeleteI am extremely delighted in for this web journal. Its a useful subject. It help me all that much to take care of a few issues. Its chance are so awesome and working style so rapid. https://vpnveteran.com/
ReplyDeleteThis comment has been removed by the author.
ReplyDeletegood
ReplyDeleteI tried it
I would like to ask if I can store the data in more than one Google sheets ( or change the Google sheet ) after I publish a form html
Is there a way a user after submitting the form can update their response ?
ReplyDeleteThis is truly a decent and useful, containing all data furthermore greatly affects the new innovation. A debt of gratitude is in order for sharing it lemigliorivpn.com
ReplyDelete