What is a formdata?

FormData is a JavaScript object that holds a set of form field names and values, including files, ready to be sent with fetch.

Calling new FormData(form) reads a form element and collects every field that would be sent in a normal submit: fields with a name that are not disabled, checked checkboxes and radio buttons, and chosen files. You can also build one by hand with append.

It is the simplest way to send a form from JavaScript without reloading the page. Pass it as the body of a fetch and the browser sends it as multipart/form-data. Do not set the Content-Type header yourself, because the browser has to add a boundary marker to it.

This is the pattern to use with a form backend when you want to stay on the page. Add an Accept: application/json header and FormTango answers with JSON in place of a redirect.

javascript
form.addEventListener('submit', async (event) => {
  event.preventDefault();
  const response = await fetch(form.action, {
    method: 'POST',
    headers: { Accept: 'application/json' },
    body: new FormData(form),
  });
  const result = await response.json();
});

Related