📋 Forms Submit and Reload Page — Not Anymore!
Traditional form submission reloads page. FormData + Fetch sends form data asynchronously. No page reload, better UX.
📝 Basic FormData
<form id="myForm">
<input type="text" name="name" value="Alice">
<input type="email" name="email" value="alice@example.com">
<button type="submit">Submit</button>
</form>
<script>
document.getElementById('myForm').addEventListener('submit', async (e) => {
e.preventDefault();
const formData = new FormData(e.target);
const response = await fetch('/api/submit', {
method: 'POST',
body: formData
// No Content-Type header!
});
const result = await response.json();
console.log('Submitted:', result);
});
</script>
🎯 Advanced FormData
// Add extra fields
const formData = new FormData();
formData.append('name', 'Alice');
formData.append('email', 'alice@example.com');
// Add file
const fileInput = document.getElementById('file');
const file = fileInput.files[0];
formData.append('avatar', file);
// Append array (multiple values)
const hobbies = ['reading', 'coding', 'gaming'];
hobbies.forEach(h => formData.append('hobbies[]', h));
// Get values
for (let [key, value] of formData) {
console.log(`${key}: ${value}`);
}
// Check if has field
formData.has('name'); // true
// Delete field
formData.delete('name');
💡 Benefits
- No page reload
- Supports file uploads
- Same as form submit (server expects multipart/form-data)
- Works with any form (including files)
- Progress tracking with XMLHttpRequest
“Form submission reloaded page, lost scroll position. Switched to FormData + Fetch. Smooth, no reload. Much better UX.”
