FormData() and the formdata event

I initially planned to write one article about the form element and JavaScript as mentioned in the last article, but soon realized that there is just too much stuff. So, as a start, we have a look at FormData() and the formdata event.

FormData() #

Let's start with the FormData() constructor. It lets you construct a set of key/value pairs representing form fields and their values.

const form = document.querySelector("form");
const formData = new FormData(form);

fetch('/whatever', {
method: 'POST',
body: formData
})
.then(response => response.json())
.then(result => {
console.log('Success:', result);
})
.catch(error => {
console.error('Error:', error);
});

In this example we use our form as a parameter for FormData(), so it will be populated with the forms current keys/values.

You can also add key/value pairs.

formData.append('json', 'true');

This way you can easily check on the server-side what request should be sent back.

Furthermore, there are various other methods available, like delete(), set(), has() and more to modify the data.

Browser support is very good and even supported in old browsers like Internet Explorer. Save to use with default server-side form handling as a fallback.

FormDataEvent #

I already knew about FormData() but only recently learned about the formdata event.

The event is fired when submitting a form or when you construct a FormData object.

const form= document.querySelector('form');

form.addEventListener('submit', (e) => {
// fires the formdata event
new FormData(formElem);

e.preventDefault();
});

formElem.addEventListener('formdata', (e) => {
// send data to server and update UI after response
// e.formData has all the data from the form
});

Browser support is pretty good, but it is not supported in Internet Explorer and more important also not in Safari. So, you either have to use a pollyfill for unsupported browsers or bet on progressive enhancement and use the server-side fallback for IE and Safari. As it is sadly still not supported in Safari I would stick to FormData() directly in the submit handler for the time being though.

Resources #

MDN: FormDataEvent https://developer.mozilla.org/de/docs/Web/API/FormDataEvent
MDN: FormData https://developer.mozilla.org/de/docs/Web/API/FormData