FormData
Oluwapelumi Famakinde
Frontend Developer | Bachelor's in Computer Software Engineering
FormData is an API in JavaScript that provides a way to easily construct and manipulate sets of key/value pairs representing form fields and their values in an HTML <form> element. It's commonly used for working with forms in web applications, especially when you need to collect data from users and submit it to a server.
Here are the key aspects of FormData:
const formData = new FormData(formElement);
formData.append("fieldName", "fieldValue");
For example, if you have an input field with the name "username," you can append its value to the FormData object like this:
formData.append("username", "john_doe");
You can also directly set the values of form fields by using the set() method:
formData.set("fieldName", "fieldValue");
领英推荐
const username = formData.get("username");
const email = formData.get("email");
fetch("/submit-form",
{ method: "POST",
body: formData,
})
.then((response) => response.json())
.then((data) => {
// Handle the server's response
});
const fileInput = document.querySelector("input[type='file']"); formData.append("file", fileInput.files[0]);
formData.delete("fieldName");
In summary, FormData is a JavaScript API that simplifies the process of working with HTML forms and their data. It's particularly useful when you need to collect, manipulate, and send form data to a server for processing, making it a key component of web form handling in modern web development.