Using FormData And Enhancing Forms With JavaScript

Jason Knights dissects a form that’s:

  1. not a form
  2. 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 the FormData 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.

Published by Bramus!

Bramus is a frontend web developer from Belgium, working as a Chrome Developer Relations Engineer at Google. From the moment he discovered view-source at the age of 14 (way back in 1997), he fell in love with the web and has been tinkering with it ever since (more …)

Leave a comment

Your email address will not be published. Required fields are marked *

This site uses Akismet to reduce spam. Learn how your comment data is processed.