With the form nicely styled we are ready to do something with it.

We will intercept the submit event attached to the form, grab the data and send it to our backend. This is done with plain frontend JavaScript. Bear with me, I’ll keep frontend to a minimum. Node.js will come soon into play 🙂

From there, on the Node.js side we’ll use the Airtable API send data. I’ll also briefly introduce you to Airtable.

Start your work from this project: https://glitch.com/edit/#!/node-course-project-newsletter-a

Rename the public/client.js file, and name it public/form.js. Also change the filename in the views/index.html file.

In there, we start by creating an event listener for the DOMContentLoaded event, so we only execute the JavaScript when the DOM is ready:

document.addEventListener("DOMContentLoaded", () => {

})

Inside this callback, we attach a submit event listener to the form:

document.addEventListener("DOMContentLoaded", () => {
  document.querySelector('form').addEventListener('submit', (event) => {

  })
})

Here we stop the event propagation, and we prevent the default behavior:

event.stopPropagation()
event.preventDefault()

Now when we submit the form, nothing happens. The browser is instructed to not automatically do what it does normally without JavaScript.

Next up, we get the form data:

const name = document.querySelectorAll('form input[name="name"]')[0].value
const email = document.querySelectorAll('form input[name="email"]')[0].value

Here’s the full code:

document.addEventListener("DOMContentLoaded", () => {
  document.querySelector('form').addEventListener('submit', (event) => {
    event.stopPropagation()
    event.preventDefault()

    const name = document.querySelectorAll('form input[name="name"]')[0].value
    const email = document.querySelectorAll('form input[name="email"]')[0].value
  })
})

Now, we intercepted the form data. We need to send it to our server to process.

First we create a POST endpoint using Express in our server.js file.

We add

app.use(express.json())

after we create the Express app, as we’ll send data in the application/json format, and we need to tell Express to use the JSON middleware to process it.

Then we add the /form endpoint:

app.post('/form', (req, res) => {
  console.log(req.body.name)
  console.log(req.body.email)

  res.end()
})

In the frontend, I include Axios by adding

<script src="https://unpkg.com/axios/dist/axios.min.js"></script>

to the index.html file. Axios is a powerful network library which makes network requests easy. Read more about it at https://flaviocopes.com/axios/.

Inside our submit event callback, we add

axios.post('/form', {
  name,
  email
})

Tip: ignore the red bubble saying ‘axios’ is not defined in Glitch. It will work.

That’s it! Now our backend code receives the data correctly.

We are ready to interact with the Airtable API in the next lesson

Project now: https://glitch.com/edit/#!/node-course-project-newsletter-b


Go to the next lesson