Form Serialization Patterns
What you'll learn: How to convert form data into different formats (JSON, URL-encoded) and choose the right one for your API.
When you submit form data to a server, you need to package it in a format the server expects. Think of serialization like packing a suitcase—the same clothes can be folded different ways depending on where you're going.
Common Serialization Formats
URL-encoded (application/x-www-form-urlencoded) is the default format for forms. It looks like a query string: name=John&email=john@example.com&age=30. This works well for simple text data.
JSON (application/json) structures data as JavaScript objects: {"name":"John","email":"john@example.com","age":30}. Modern APIs often prefer this format because it handles nested data elegantly.
multipart/form-data is required for file uploads (you've already learned this with FormData).
Converting FormData to Different Formats
const form = document.querySelector('form');
const formData = new FormData(form);
// Convert to URL-encoded string
const urlEncoded = new URLSearchParams(formData).toString();
// Result: "name=John&email=john@example.com"
// Convert to JSON object
const jsonData = Object.fromEntries(formData);
const jsonString = JSON.stringify(jsonData);
// Result: '{"name":"John","email":"john@example.com"}'
Choosing the Right Format
Use URL-encoded for simple forms and backward compatibility. Use JSON when working with modern REST APIs, especially if you have nested or complex data. Use multipart/form-data (FormData directly) when uploading files.
Key Takeaway: Form serialization transforms your form data into the format your server expects—URL-encoded for traditional forms, JSON for modern APIs, and multipart for file uploads.