How to submit a form using javascript

Learn how to submit a form using javascript with practical examples, diagrams, and best practices. Covers javascript, forms, submit development techniques with visual explanations.

Submitting Forms with JavaScript: A Comprehensive Guide

Hero image for How to submit a form using javascript

Learn various methods to submit HTML forms using JavaScript, from basic programmatic submission to advanced AJAX techniques, ensuring a smooth user experience.

Submitting forms is a fundamental part of web development, allowing users to send data to a server. While the default HTML form submission works well, JavaScript provides powerful ways to control and enhance this process. This article explores different techniques for submitting forms using JavaScript, including direct submission, AJAX, and handling form data.

Understanding Basic Form Submission

Before diving into JavaScript-driven submissions, it's important to understand how HTML forms work natively. A form typically has an action attribute pointing to the server-side script that will process the data, and a method attribute (GET or POST) defining how the data is sent. When a user clicks a submit button, the browser collects the form data and sends it to the specified URL.

<form id="myForm" action="/submit-data" method="POST">
  <label for="username">Username:</label>
  <input type="text" id="username" name="username" required>
  <br>
  <label for="email">Email:</label>
  <input type="email" id="email" name="email" required>
  <br>
  <button type="submit">Submit Form</button>
</form>

A basic HTML form structure.

Programmatic Form Submission with JavaScript

JavaScript allows you to trigger a form submission programmatically, without the user explicitly clicking a submit button. This is useful for scenarios like auto-saving, timed submissions, or when submission is part of a larger JavaScript-driven workflow. The simplest way is to use the submit() method of the form element.

document.getElementById('myForm').submit();

Submitting a form programmatically using its submit() method.

flowchart TD
    A[User Interaction/Event] --> B{Should Form Submit?}
    B -->|Yes| C[Get Form Element]
    C --> D["Call form.submit()"]
    D --> E[Browser Sends Data]
    E --> F[Page Reloads/Navigates]
    B -->|No| G[Prevent Submission]

Flowchart of programmatic form submission.

Asynchronous Form Submission (AJAX)

For a more dynamic user experience, you can submit form data asynchronously using AJAX (Asynchronous JavaScript and XML). This prevents a full page reload, allowing you to update parts of the page with server responses, display loading indicators, or handle errors without disrupting the user's flow. The fetch API or XMLHttpRequest are common tools for this.

When using AJAX, you typically prevent the default form submission and then manually collect the form data to send it via a network request. The FormData API is incredibly useful for easily collecting all form fields.

const form = document.getElementById('myForm');

form.addEventListener('submit', async (event) => {
  event.preventDefault(); // Prevent default form submission

  const formData = new FormData(form); // Collect form data

  try {
    const response = await fetch(form.action, {
      method: form.method,
      body: formData
    });

    if (response.ok) {
      const result = await response.json(); // Or response.text()
      console.log('Form submitted successfully:', result);
      // Update UI, show success message, etc.
    } else {
      console.error('Form submission failed:', response.statusText);
      // Handle errors, show error message
    }
  } catch (error) {
    console.error('Network error:', error);
  }
});

Asynchronous form submission using the fetch API and FormData.

Handling Form Data for AJAX Submissions

The FormData object is the most convenient way to prepare form data for AJAX requests. It automatically encodes the form fields into a format suitable for POST requests (multipart/form-data or application/x-www-form-urlencoded). For GET requests or when sending JSON, you might need to convert FormData to a URL search string or a JSON object.

// Converting FormData to a URLSearchParams string for GET requests
const formData = new FormData(form);
const searchParams = new URLSearchParams(formData);
console.log(searchParams.toString()); // e.g., "username=test&email=test%40example.com"

// Converting FormData to a JSON object
const jsonObject = {};
formData.forEach((value, key) => {
  jsonObject[key] = value;
});
console.log(JSON.stringify(jsonObject)); // e.g., {"username":"test","email":"test@example.com"}

Converting FormData to URLSearchParams or JSON.

sequenceDiagram
    participant User
    participant Browser
    participant JavaScript
    participant Server

    User->>Browser: Fills form and clicks submit
    Browser->>JavaScript: 'submit' event fired
    JavaScript->>JavaScript: event.preventDefault()
    JavaScript->>JavaScript: Collects FormData
    JavaScript->>Browser: Initiates fetch() request
    Browser->>Server: Sends AJAX request (POST/GET)
    Server-->>Browser: Sends response (JSON/HTML)
    Browser->>JavaScript: Receives response
    JavaScript->>JavaScript: Processes response
    JavaScript->>User: Updates UI (e.g., success message)

Sequence diagram of an AJAX form submission.