offers methods to manipulate this data, including
HTML forms are a crucial component of interactive websites, enabling users to provide data that can be dispatched to a server for further processing. This data is typically structured as form data, consisting of a series of key-value pairs, where the keys correspond to the names of the form fields, and the values represent the user's input.
FormData interface, a part of the Web API. The
FormData object allows you to compile a set of key-value pairs, which can be dispatched using an XMLHttpRequest. Although its primary application is for transmitting form data, the
FormData object can be utilized independently from forms to transfer keyed data.
Here's an extended example demonstrating how the
let formData = new FormData(); // Append new data to the form formData.append('username', 'JohnDoe'); formData.append('email', 'email@example.com'); console.log(formData.get('username')); // JohnDoe // Delete a value from the form data formData.delete('username'); console.log(formData.get('username')); // null let request = new XMLHttpRequest(); request.open('POST', 'submitform.php'); request.send(formData);
In this example, a new
FormData object is instantiated, and two key-value pairs are added to it using the
append() method. The
get() method is then used to retrieve the value of the 'username' field, and the
delete() method is used to remove the 'username' field from the form data. Finally, an XMLHttpRequest is created and opened with the "POST" method and the URL of the server-side script that will handle the form data. The form data is then dispatched to the server using the
send() method of the XMLHttpRequest.