Home > Web Front-end > JS Tutorial > Everything you need to know about the `FormData` object in JavaScript

Everything you need to know about the `FormData` object in JavaScript

Patricia Arquette
Release: 2024-11-23 02:22:10
Original
830 people have browsed it

Sve što treba da znate o `FormData` objektu u JavaScript-u

When working with data from HTML forms in JavaScript, you often encounter the need to collect, manipulate, and send that data to the server. This is where FormData comes in — a powerful and flexible form management API. In this post, we'll explain in detail how FormData works, its benefits, and how you can use it in real-world scenarios.


What is FormData?

FormData is an embedded JavaScript object that enables:

  • Simple data collection from HTML forms.

  • Sending that data to the server using fetch API or XMLHttpRequest.

  • Work with binary data, like files.

This object automatically formats data according to the multipart/form-data MIME type, making it ideal for sending complex data, including files.


How to create a FormData object?

Creating an empty FormData object

If you want to add data manually, use the empty FormData constructor:

const formData = new FormData();
formData.append('username', 'Jelena');
formData.append('email', 'jelena@example.com');
Copy after login
Copy after login

Creating a FormData object from a form

If you have an HTML form, you can directly pass the form reference to the FormData constructor, which will automatically collect all data from it.

const form = document.getElementById('registrationForm');
const formData = new FormData(form);
Copy after login

Adding data

Data is appended using the .append(key, value) method:

formData.append('firstName', 'Jelena');
formData.append('lastName', 'Petković');
Copy after login

If adding a file from , just use .files[0]:

const fileInput = document.getElementById('profilePicture');
formData.append('profilePicture', fileInput.files[0]);
Copy after login

Reading data

To iterate through the data in the FormData object, use a for...of loop along with the .entries() method:

for (let [key, value] of formData.entries()) {
  console.log(`${key}: ${value}`);
}
Copy after login

Sending FormData data to the server

FormData is ideal for sending data to the server using the fetch API. Here is a simple example:

fetch('https://example.com/api/register', {
  method: 'POST',
  body: formData, // Automatski formatiran kao multipart/form-data
})
  .then(response => response.json())
  .then(data => console.log('Uspešno registrovano:', data))
  .catch(error => console.error('Greška:', error));
Copy after login

No need to manually set the Content-Type header; FormData does this automatically.


Advantages of FormData

  1. Working with files

    FormData allows you to easily add and send files directly from fields.

  2. Automatic Serialization

    Instead of manually formatting the data, FormData automatically formats it into multipart/form-data.

  3. Flexibility

    Easy management of key-value pairs, including the ability to iterate and update data.

  4. Binary data support

    It is ideal for sending binary data such as images, PDFs or other files.


Example from practice: Registration form

Here is a complete example where we collect data from the form and send it to the server:

HTML Form

const formData = new FormData();
formData.append('username', 'Jelena');
formData.append('email', 'jelena@example.com');
Copy after login
Copy after login

Useful tips

  • If you want to manually modify the data, use .set(key, value) instead of .append().

  • You can check if a particular key exists using the .has(key) method.

  • To remove data, use .delete(key).


Conclusion

FormData is a powerful tool for working with form data. It allows easy collection, manipulation and sending of data, even when working with files. Its flexibility and easy integration with modern JavaScript APIs make it indispensable for many web applications.

The above is the detailed content of Everything you need to know about the `FormData` object in JavaScript. For more information, please follow other related articles on the PHP Chinese website!

source:dev.to
Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Latest Articles by Author
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template