When you submit a form with JavaScript instead of a page reload, you need a way to collect the field values and send them. You could read each input by hand — or you could use FormData, which does it in one line. It reads every named field in a form, including files, and packages them ready for fetch().
Create it from a form element, and it picks up every input, select and textarea that has a name attribute.
const form = document.querySelector("#signup-form");
form.addEventListener("submit", async (event) => {
event.preventDefault();
const data = new FormData(form);
const response = await fetch("/api/signup", {
method: "POST",
body: data
});
console.log("Saved:", response.ok);
});
You can also build a FormData object by hand, adding values with append() and reading them back with get() or getAll() — handy for debugging or adding fields the form does not have.
const data = new FormData();
data.append("username", "arhan");
data.append("avatar", fileInput.files[0]); // a file, no extra work
console.log(data.get("username")); // "arhan"
console.log(data.has("avatar")); // true
A common beginner mistake is setting the Content-Type header by hand when sending FormData with fetch(). Do not do it — the browser sets the correct multipart/form-data header with the right boundary automatically, and a hand-set header will break the upload.
// Wrong: this breaks file uploads
fetch("/api/upload", { method: "POST", headers: { "Content-Type": "multipart/form-data" }, body: data });
// Right: let the browser set the header
fetch("/api/upload", { method: "POST", body: data });
FormData also handles checkboxes and multi-selects naturally: unchecked boxes are simply absent, and fields with the same name appear multiple times, which getAll() returns as an array.
FormData turns form submission into three lines: build it from the form, send it with fetch, and let the browser handle the encoding. Use it whenever a form needs JavaScript handling, and file uploads come free.
Top comments (0)