Course contentsShow
← Web Development
Lesson 890 of 2,98216. Forms and ValidationFree lesson

Submitting Forms with Fetch

Sending FormData objects using the Fetch API with proper headers and request configuration.

Submitting Forms with Fetch

What you'll learn: How to send form data to a server using the Fetch API instead of traditional form submissions.

The Core Idea

Now that you know how to work with FormData objects, you can combine them with Fetch to submit forms programmatically. This gives you complete control over the submission process—you can validate data first, show loading states, handle errors gracefully, and update the page without a full reload.

When you pass a FormData object directly to fetch() as the body, the browser automatically sets the correct Content-Type header (multipart/form-data) and formats everything properly. You just need to specify the HTTP method (usually POST) and the destination URL.

Basic Form Submission

const form = document.querySelector('form');

form.addEventListener('submit', async (event) => {
  event.preventDefault(); // Stop traditional submission
  
  const formData = new FormData(form);
  
  try {
    const response = await fetch('/submit', {
      method: 'POST',
      body: formData // Browser handles headers automatically
    });
    
    if (!response.ok) {
      throw new Error('Submission failed');
    }
    
    const result = await response.json();
    console.log('Success:', result);
  } catch (error) {
    console.error('Error:', error);
  }
});

Why This Matters

Think of it like sending a package: traditional form submission is like dropping it at the post office and walking away. Using Fetch with FormData is like having a tracking number—you can monitor the delivery, handle problems, and get confirmation when it arrives.

Key Takeaway: Combining FormData with Fetch gives you full control over form submissions, allowing you to handle the request and response programmatically while the browser manages the proper formatting automatically.