Submit HTML Forms with Fetch API
The FormData interface reads form controls and sends them using the browser's form encoding. It is convenient for progressive enhancement and file uploads.
Submit a form
const form = document.querySelector('#contact-form');
form.addEventListener('submit', async (event) => {
event.preventDefault();
const response = await fetch(form.action, {
method: 'POST',
body: new FormData(form),
headers: { 'Accept': 'application/json' }
});
const result = await response.json();
if (!response.ok) {
showErrors(result.errors || {});
return;
}
document.querySelector('#feedback').textContent = result.message;
form.reset();
});
Validation responsibilities
Use browser constraints for immediate feedback, but repeat validation on the server. Return clear field errors and suitable status codes. Keep success and error messages accessible to screen readers.
Security
Protect state-changing forms with CSRF tokens, verify the user's permission, and escape output when displaying submitted values. A hidden form field is not proof that a request is legitimate.