Developers seem to have invented a thousand different ways to avoid using HTML forms these days, which constantly makes me think we're all reinventing the wheel. Surely there's a simpler, more grounded way to capture form data that uses the foundations that HTML already provides us? Yep, there is: the FormData() API!
Bramus has done a great job of outlining the issue and solution in this post, which roughly boils down to this quote:
AsFormDatacaptures all the formβs key-value pairs, applying Progressive Enhancement on forms becomes pretty easy:
- Build a regular HTML form that submits its data to somewhere
- Make it visually interesting with CSS
- Using JavaScript, hijack the formβs
submitevent and, instead, send its contents β captured throughFormDataβ usingfetch()to the defined endpoint.
They also touch on how to convert the form data to JSON and some other quick tricks. The whole experiment can be seen on CodePen.