This content originally appeared on Bram.us and was authored by Bramus!
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", (event) => {
event.preventDefault();
const form = event.currentTarget;
fetch(form.action, {
method: form.method,
body: new FormData(form) // <-- This!
})
.then(r => r.json())
.then(json => console.log(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.
This content originally appeared on Bram.us and was authored by Bramus!
Bramus! | Sciencx (2022-03-21T21:43:28+00:00) Using FormData And Enhancing Forms With JavaScript. Retrieved from https://www.scien.cx/2022/03/21/using-formdata-and-enhancing-forms-with-javascript/
Please log in to upload a file.
There are no updates yet.
Click the Upload button above to add an update.