Skip to content

Send form data with fetch, without CORS surprises

Post a form with fetch from any website: JSON or FormData, the CORS preflight, reading errors and retrying safely.

2 min read

On this page

Sending a form with JavaScript keeps visitors on the page and lets you show your own messages. It also brings CORS into the picture, the browser rule that decides whether a page on one address may read the answer from another. Most "my form does not work" reports from custom code come down to a few details. Here they are, with working code.

FormData or JSON

You can send the form as FormData or as JSON. Both reach the same endpoint and the same flows.

  • FormData takes the form exactly as it is, files included. Build it with new FormData(form) and do not set Content-Type: the browser adds it with the boundary the body needs.
  • JSON suits apps that keep answers in state rather than in a form element. Set Content-Type: application/json and send the field keys as property names.

The preflight request

For a JSON body, or any custom header, the browser first sends an OPTIONS request asking whether the real request is allowed. Only when the answer says yes does it send the POST. A plain FormData post skips this step. The Formpik endpoint answers preflights for you, so both kinds work from any website the form allows.

Allowed websites

Each Formpik form can list the websites allowed to post to it, subdomains included. A post from anywhere else is refused, but it still gets CORS headers, so your code can read the reason instead of seeing an opaque network error. When a working form suddenly fails after a domain change, add the new address to the list.

A complete example

const form = document.querySelector('#contact')
const status = document.querySelector('#contact-status')

form.addEventListener('submit', async event => {
  event.preventDefault()
  status.textContent = 'Sending...'

  try {
    const response = await fetch(form.action, {
      method: 'POST',
      headers: { Accept: 'application/json' },
      body: new FormData(form)
    })
    const result = await response.json()

    if (result.ok) {
      form.reset()
      status.textContent = result.message
      return
    }

    status.textContent = result.message
    console.log(result.errors)
  }
  catch {
    status.textContent = 'We could not reach the server. Please try again.'
  }
})

The Accept: application/json header matters: without it the endpoint treats the request like a classic form post and answers with a redirect.

Read the answer

  • ok: true comes with the submission id and the form's success message, plus a redirect address when the form sends people to another page.
  • ok: false comes with a message and a reason. When answers break a field rule, the status is 422 and errors holds one message per field key, ready to show next to each input.
  • A 429 means too many posts; wait before trying again.

Retry without sending twice

Networks fail. If you retry a post, send an Idempotency-Key header with a value that stays the same for that one submission, such as an id you generate when the form is shown. A repeat with the same key is answered with the first result instead of creating a second submission. Formpik also drops identical submissions within 10 seconds, which covers double clicks.

Or skip the code

The Formpik script does all of this for ordinary forms: add the script line from your source's snippet and it catches the submit, posts with fetch, shows your success and error blocks and the per-field errors.

References

Keep reading

More from the blog