Using formdata Event for AJAX Form Submissions

javascript
Published on February 3, 2020

Use-Cases of this code snippet

  • Know about the "formdata" Javscript event
  • Know how to include values of Custom Elements when submitting a <form> with AJAX

The newly introduced "formdata" event can enable the Javscript FormData object to participate in form submissions. When trying to submit a form via AJAX, this is helpful to include custom elements in the request.

The formdata event is a recent addition to browser APIs. This event is fired for a <form> element when the form's data is constructed. This usually happens when the form is submitted, but it can also be triggered on creating a new FormData object for the form.

<form id="test-form">
	<input type="text" name="name" />
	<select name="gender">
		<option value="M">Male</option>
		<option value="F">Female</option>
	</select>
	<input type="file" name="picture" />
	<button>Submit</button>
</form>
// form submit event
document.querySelector("#test-form").addEventListener('submit', function(e) {
	e.preventDefault();

	// create new FormData for the current form so that formdata event gets triggered
	new FormData(this);
});

// form formdata event
document.querySelector("#test-form").addEventListener('formdata', function(e) {
	// refers to the FormData object
	var form_data = e.formData;

	// if required we can append(), delete() or perform other operations on the FormData object

	// send AJAX request
	var xhr = new XMLHttpRequest();
	xhr.open("POST", "/ajax.php");
	xhr.send(form_data);
});

Why Introduce formdata Event ?

By default, only form elements can participate in form submissions. For example a <form>, a form's <button> and so on.

The formdata event is a part of the Form Participation API. The aim of this API is to enable Javascript objects other than the form elements to participate in form submissions also. As we can see, we can now use the FormData object to submit a form. This was not possible before.

Why enable objects to participate in form submissions ? The real reason behind this is Custom Elements which is a big thing coming up. If a developer has created a Custom Element that behaves like an <input> element, he should be able to include the Custom Element as well when submitting the form. The Form Participation API can now help in doing this.

Useful Resources

Comments
Loading Comments