Sending a form with fetch

I would like to turn the contents of a textarea in a form into the body of an email to be sent to a support email address. I am not having to deal with the backend. I am completely new to ajax and server-frontend communication.
I have decided to use the fetch polyfill. Most tutorials about fetch are about requesting data from servers. If anyone has a simple code example or link to a tutorial I would find it really helpful!

You can send data by setting {method: 'POST'} in the options parameter, and provide an appropriate body. So if you want to send the form data to the server, you might do so like

const myForm = document.querySelector('form')

myForm.addEventListener('submit', evt => {
  const data = new FormData(myForm)

  evt.preventDefault()

  fetch('foo.php', {
    method: 'POST',
    body: data
  })
  .then(res => {
    if (res.ok) {
      console.log('Success!')
    }
  })
})

This topic was automatically closed 91 days after the last reply. New replies are no longer allowed.