简体   繁体   中英

HTML form not submitting to a Google Spreadsheet

What I am trying to do is when every person fills out the form on my website all the data will be sent to the google sheet that I create for that specific contact form. I'm following a blog post https://dev.to/omerlahav/submit-a-form-to-a-google-spreadsheet-1bia

Everytime I follow the code below I get a error message saying that

Uncaught TypeError: Cannot read property 'addEventListener' of undefined

The

const form = document.forms['submit-to-google-sheet'];

is calling the form element to trigger the data within the form elements. This goes inside of the HTML for like so

<form name="submit-to-google-sheet"></form>

const scriptURL = 'Google Script Link Here';
const form = document.forms['submit-to-google-sheet'];

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))
});

BETA LINK: https://i8cp0-zzwqjbaw.instant.forestry.io/

GITHUB: assets/js/form.js I have the the code inside of this code: https://github.com/brandonpowell/pw/tree/master

Basically, you are trying to attach the event listener before the form loads into the HTML.

Option 1
Try adding your form.js at the end of the body

<html>
 <head>
  <!-- Include css and other meta data -->
 </head>
  <body>
    <!-- All other html -->

    <!-- Script tag goes at the end (when everything is loaded)-->
    <script src="form.js"></script>
  </body>
</html>

* You HTML doesn't contains body tag, it is not a valid html.

If that doesn't work try this.
Option 2

Wrap your form.js code in

window.addEventListener('load', (event) => {
 //All your code goes here...
});

Some useful resources
Window load event
Defer and Async attribute
Javascript Topics

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM