Using FormData And Enhancing Forms With JavaScript

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 …

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", (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.


Print Share Comment Cite Upload Translate
APA
Bramus! | Sciencx (2024-03-28T19:25:53+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/.
MLA
" » Using FormData And Enhancing Forms With JavaScript." Bramus! | Sciencx - Monday March 21, 2022, https://www.scien.cx/2022/03/21/using-formdata-and-enhancing-forms-with-javascript/
HARVARD
Bramus! | Sciencx Monday March 21, 2022 » Using FormData And Enhancing Forms With JavaScript., viewed 2024-03-28T19:25:53+00:00,<https://www.scien.cx/2022/03/21/using-formdata-and-enhancing-forms-with-javascript/>
VANCOUVER
Bramus! | Sciencx - » Using FormData And Enhancing Forms With JavaScript. [Internet]. [Accessed 2024-03-28T19:25:53+00:00]. Available from: https://www.scien.cx/2022/03/21/using-formdata-and-enhancing-forms-with-javascript/
CHICAGO
" » Using FormData And Enhancing Forms With JavaScript." Bramus! | Sciencx - Accessed 2024-03-28T19:25:53+00:00. https://www.scien.cx/2022/03/21/using-formdata-and-enhancing-forms-with-javascript/
IEEE
" » Using FormData And Enhancing Forms With JavaScript." Bramus! | Sciencx [Online]. Available: https://www.scien.cx/2022/03/21/using-formdata-and-enhancing-forms-with-javascript/. [Accessed: 2024-03-28T19:25:53+00:00]
rf:citation
» Using FormData And Enhancing Forms With JavaScript | Bramus! | Sciencx | https://www.scien.cx/2022/03/21/using-formdata-and-enhancing-forms-with-javascript/ | 2024-03-28T19:25:53+00:00
https://github.com/addpipe/simple-recorderjs-demo