Building Your Learning Module...
Getting things ready for you!
Find videos you like?
Save to resource drawer for future reference!
FormData is a modern JavaScript API that makes it easy to capture all form data, including files, and send it via AJAX or fetch!
const form = document.querySelector('#myForm');
form.addEventListener('submit', function(e) {
e.preventDefault();
// Create FormData from form
const formData = new FormData(form);
// Get individual values
const name = formData.get('name');
const email = formData.get('email');
console.log('Name:', name);
console.log('Email:', email);
});const formData = new FormData(form);
// Method 1: for...of loop
for (const [key, value] of formData) {
console.log(key, value);
}
// Method 2: forEach
formData.forEach((value, key) => {
console.log(key, value);
});
// Method 3: entries()
for (const entry of formData.entries()) {
console.log(entry);
}const formData = new FormData();
// append() - adds new entry (allows duplicates)
formData.append('hobby', 'reading');
formData.append('hobby', 'coding');
// set() - replaces existing or adds new
formData.set('name', 'John');
formData.set('name', 'Jane'); // Replaces John
// Other methods
formData.has('name'); // true
formData.delete('hobby'); // removes all hobby entries
formData.getAll('hobby'); // gets all hobby valuesform.addEventListener('submit', async function(e) {
e.preventDefault();
const formData = new FormData(form);
// File is automatically included!
const file = formData.get('avatar');
console.log('File:', file.name);
console.log('Size:', file.size);
console.log('Type:', file.type);
// Send to server with fetch
await fetch('/upload', {
method: 'POST',
body: formData // Don't set Content-Type!
});
});form.addEventListener('submit', async function(e) {
e.preventDefault();
const formData = new FormData(form);
try {
const response = await fetch('/api/submit', {
method: 'POST',
body: formData
// Don't set Content-Type!
// Browser sets it automatically
});
const data = await response.json();
console.log('Success:', data);
} catch (error) {
console.error('Error:', error);
}
});new FormData(form) - From form elementnew FormData() - Empty FormData.get(name) - Get first value.getAll(name) - Get all values.has(name) - Check if exists.keys() - Get all keys.values() - Get all values.append(name, value) - Add (allows duplicates).set(name, value) - Set (replaces existing).delete(name) - Remove entryfor (const [k, v] of formData)formData.forEach((v, k) => ...)formData.entries() - Iterator