0

I have created a form in Html to post data to a Googlesheets and it is working fine. When I try to seperate the Javascript file and use it inside html file the script is not working.

What might be the problem and please help me out to solve it.

This is my script.js file:

const scriptURL = 'https://script.google.com/macros/s/AKfycbxRJo4gGwmTHCh6jXO2fcICFJQwI1LwEi7dPI_7vbLq8r4Q-6hbzXprJWIvYn6N7JL_Vw/exec'
    const form = document.forms['submit-to-google-sheet']
    const msg = document.getElementById("msg")

    form.addEventListener('submit', e => {
        e.preventDefault();
        fetch(scriptURL, { method: 'POST', body: new FormData(form)})
        .then(response => {
            msg.innerHTML = "We will get back to you!"
            setTimeout(function(){
                msg.innerHTML = ""
            },5000)
            form.reset()
        })
        .catch(error => console.error('Error!', error.message))
    })

I have tried to use it in Html file with the tag:

<script src="script.js"></script>

If I use it inside html file it is properly working. I want to split the script file apart from my html file and not able to perform the functionality even using it from outside or html file with linking it to script file.

sai charan
  • 67
  • 2
  • 8
  • 2
    Assuming the URL to the script itself is not wrong (check your browser console for 404 errors), it is probably embedded "too early", before the elements you are trying to access there even exist. – CBroe Sep 26 '22 at 12:55
  • 1
    Use your browser's debugging tools. On the network tab, is the script successfully fetched from the server? On the console, are there any errors? In the script debugger, what happens when debugging the code? – David Sep 26 '22 at 12:57
  • in the console I'm getting the error~ Uncaught TypeError: Cannot read properties of undefined (reading 'addEventListener') at contact.js:5:6 – sai charan Sep 26 '22 at 13:00
  • 1
    So exactly as @CBroe mentions, your script is running before those elements have been added to the page. Try adding `defer` to your script tag attributes, or move your script tag to the bottom of your page so it only gets created (and executed) after all the other page content. Or wrap the whole code in a `document.addEventListener( 'DOMContentLoaded', () => { ...code... })` – somethinghere Sep 26 '22 at 13:02
  • 1
    yup it worked as you said, thanks for your help @somethinghere – sai charan Sep 26 '22 at 13:07

1 Answers1

0

If the html and the script file are inside the same directory, try this

<script defer src="./script.js"></script>

defer tells the browser to load the script file only after the html is loaded completely. The ./ before the file name is to specify that the file that you're refereing to(script.js) is on the same directory as the html file.

Saurav Ghimire
  • 500
  • 2
  • 9