How to Submit a Form Using JavaScript
Learn how to send form data with fetch, handle JSON vs FormData, show loading states, and deal with errors.
Submitting forms with JavaScript gives you full control over the user experience: you can show loading states, validate before sending, submit in the background, and display friendly error messages.
In this guide you’ll learn two common patterns:
- Send JSON with
fetch - Send
FormData(recommended for files)
1) Submit JSON with fetch
This pattern is great when you’re sending simple text fields and your backend accepts JSON.
2) Submit FormData (works with files)
FormData matches how HTML forms submit data and is the best option when you need file uploads.
3) Show loading & success states
Always give users feedback. At minimum: disable the submit button while the request is in progress and show a success message.
4) Handle errors cleanly
Treat non-2xx responses as failures and show a helpful message. If your backend returns JSON error details, parse them.
