form data object
Form data objects are used to store and send form data to a server. It can be used to store any type of data in key-value pairs, including strings, numbers, and even files. Form data objects are created using the HTMLFormElement.createFormData() method. This method takes an array of objects and creates a form data object from the key-value pairs of the objects.
// Create the form data object
var formData = new FormData();
// Add the data to the object
formData.append('name', 'Raju');
formData.append('age', '25');
formData.append('image', imageFile);
Form data objects can also be used to send data to the server using the XMLHttpRequest.send() method. The data is encoded using the multipart/form-data encoding type.
// Create the request
var request = new XMLHttpRequest();
// Set the method, url and encoding type
request.open('POST', '/upload', true);
request.setRequestHeader('Content-Type', 'multipart/form-data');
// Send the request
request.send(formData);
Form data objects can also be used to read data from the server. The FormData.get() method can be used to read a specific value from the object.
// Get the name field from the form data object
var name = formData.get('name');