FormData Demystified: Elevating Form Submissions in Modern Web Applications

Optimize Data Transmission from Client to Server with This Essential JavaScript Tool

In Almost every web application we have to collection user data via HTML forms.

And to collect data we simply use javascript inbuilt objects and send them as it is via axios or fetch.

While doing so, we un-intentionally leaving few validations and missing out some inbuilt features. Like FormData. FormData presents a sophisticated approach to managing form data, offering a seamless solution.

How to Create a FormData Object

const formData = new FormData();

There are multiple methods available of this formData object:

  • append() : used to append a key-value pair to object. If the key already exists, previous value will be replaced.
  • delete(): used to deletes a key-value pair,
  • entries(): returns an Iterator object that you can use to loop through the list the key value pairs in the object,
  • get(): used to return the value for a key. If multiple values are appended, it returns the first value,
  • getAll(): used to return all the values for a specified key,
  • has(): used to check if there’s a key,
  • keys(): returns an Iterator object which you can use to list the available keys in the object,
  • set(): used to add a value to the object, with the specified key. This is going to replace the value if a key already exists,
  • values(): returns an Iterator object for the values of the FormData object.

Benefits:

  1. If your form doesn’t requires any validation, no need to collect the data one by one, simply grab the form reference by JS and pass that reference to formData object, it will automatically extract out the information.
    Name of the control will be come the key.
// React Code

<form id='myForm' onSubmit={(e)=> {
e.preventDefault();
const formData = new FormData(document.getElementById('myForm'))
console.log([...formData.entries()]);

}}>

<input type="text" name="fName" id="fName" />
<input type="text" name="lName" id="lName" />
<button type="submit"> Submit </button>
</form>

2. No Encoding Required.

When we send data via URL certain characters needs to be encoded.

Without Form Data:

let params = {
username: 'example_username',
password: 'example_password'
};

// Extra Work: Convert the object to a query string
let queryString = Object.keys(params)
.map(key => `${encodeURIComponent(key)}=${encodeURIComponent(params[key])}`)
.join('&');


fetch('https://example.com/api/login', {
method: 'POST',
headers: {
// Extra Work: Setting the header for server
// Not Manadatory, But a good Practice.
'Content-Type': 'application/x-www-form-urlencoded'
},
body: queryString
})

With Form Data:

// Create a new FormData object
let formData = new FormData();

// Append the form data to the FormData object
formData.append('username', 'example_username');
formData.append('password', 'example_password');

// Now you can send `formData` to the server using AJAX or fetch
// Example using fetch
fetch('https://example.com/api/login', {
method: 'POST',
body: formData
})
.then(response => response.json())
.then(data => {
console.log(data);
})
.catch(error => {
console.error('Error:', error);
});

3. Best Choice for Uploading files:

Without Form Data:

const fileInput = document.getElementById('fileInput');
fileInput.addEventListener('change', function(event) {
const file = event.target.files[0];
if (file) {
// Extra work, can be avoided.
const reader = new FileReader();
reader.onload = function(event) {
const fileData = event.target.result; // fileData is a base64-encoded string or Blob
uploadFile(fileData);
};
reader.readAsArrayBuffer(file);
}
});

With Form Data:

const fileInput = document.getElementById('fileInput');
fileInput.addEventListener('change', function(event) {
const file = event.target.files[0];
if (file) {
uploadFile(file);
}
});

function uploadFile(file) {
// Create a new FormData object
const formData = new FormData();

// Append the file to the FormData object
formData.append('file', file);

// send the formData in API request
}

Corner Cases:

null and undefined will be covered to string, equivalent and will be sent in API

object needs to be converted to string before sending, other wise we will get [object Object] due to JS auto type conversion.

Arrays will be converted to strings.

Availability:

Not Available in Node JS.

FormData is actually part of both JavaScript and the browser environment. It’s a built-in JavaScript object. While it’s implemented in the browser environment, it’s accessible and usable within JavaScript code running in that environment.

Support: In All Browsers.

--

--