Jason Knights dissects a form that’s:
- not a form
- relies entirely on JS to handle the form submission
He then takes his own approach that uses an actual <form>
that can be submitted, along with some extra JS sprinkled on top to prevent a full reload.
By using PROPER
name=""
in the markup and a proper form, all we need to hook is the form, prevent the submit, pull theFormData
and send it.
Unlike Jason I wouldn’t resort to XHR, but go with fetch()
instead, like so:
document.getElementById("form").addEventListener("submit", async (event) => {
event.preventDefault();
const form = event.currentTarget;
const r = await fetch(form.action, {
method: form.method,
body: new FormData(form),
});
const json = await r.json();
// do something with json
});
Using FormData And Enhancing Forms With JavaScript →
FormData – Web APIs | MDN →
💵 This linked article is stuck behind Medium's metered paywall, which may prevent you from reading it. Open the link in an incognito window to bypass Medium's ridiculous reading limit.