Creating FormData Without Forms
You'll learn how to build FormData objects programmatically, without relying on existing HTML forms.
The Core Idea
While FormData is commonly used with actual <form> elements, you can construct these objects entirely from scratch in JavaScript. This is useful when you need to send form-like data to an API but don't have (or want) an actual HTML form on the page—perhaps you're building a single-page app, working with data from various sources, or creating dynamic payloads.
Building FormData Manually
Simply create a new FormData instance without passing anything to the constructor:
const formData = new FormData();
// Add fields using .append()
formData.append('username', 'alice123');
formData.append('email', 'alice@example.com');
formData.append('age', '25');
// Add a file from a file input
const fileInput = document.querySelector('#avatar');
if (fileInput.files[0]) {
formData.append('avatar', fileInput.files[0]);
}
// Send it
fetch('/api/users', {
method: 'POST',
body: formData
});
When to Use This Approach
- Dynamic forms: Building requests from user interactions spread across multiple UI elements
- Programmatic uploads: Sending files obtained through JavaScript APIs (camera, drag-and-drop)
- Combining sources: Merging data from localStorage, user input, and uploaded files into one request
- No form needed: Your UI doesn't have traditional form elements, but you still need multipart encoding
This approach gives you complete control over what gets sent, without being tied to HTML structure.
Key Takeaway: You can create FormData objects from scratch using new FormData() and .append(), giving you flexibility to build multipart requests programmatically without any HTML forms.