AJAX - Form Data in AJAX

1) What is Form Data?

When you submit a <form> in HTML normally, the browser encodes the fields and sends them to the server.
With AJAX, you can collect form fields with JavaScript and send them asynchronously (without refreshing the page).

AJAX supports multiple encodings:

  • application/x-www-form-urlencoded (default HTML form style)

  • multipart/form-data (for file uploads, already explained)

  • application/json (common in APIs)


2) Collecting Form Data with JavaScript

Example HTML form

<form id="loginForm">
  <input type="text" name="username" value="john123">
  <input type="password" name="password" value="mypassword">
  <button type="submit">Submit</button>
</form>

3) Using FormData (easiest way)

The FormData object automatically gathers all <input>, <select>, <textarea> values.

const form = document.getElementById("loginForm");

form.addEventListener("submit", (e) => {
  e.preventDefault(); // prevent normal form submit

  const formData = new FormData(form);

  fetch("/login", {
    method: "POST",
    body: formData
  })
  .then(res => res.json())
  .then(data => console.log("Response:", data))
  .catch(err => console.error("Error:", err));
});

Notes:

  • FormData handles all form fields automatically.

  • For file inputs, it also includes the file(s).

  • You don’t need to set Content-Type → browser will set multipart/form-data with boundary.


4) Sending as application/x-www-form-urlencoded

Sometimes servers expect classic form encoding (like a regular HTML form).
You can build the query string manually or use URLSearchParams.

const form = document.getElementById("loginForm");

form.addEventListener("submit", (e) => {
  e.preventDefault();

  const formData = new FormData(form);
  const params = new URLSearchParams(formData);

  fetch("/login", {
    method: "POST",
    headers: { "Content-Type": "application/x-www-form-urlencoded" },
    body: params
  })
  .then(res => res.json())
  .then(data => console.log("Response:", data));
});

This sends data like:

username=john123&password=mypassword

5) Sending as JSON (for APIs)

Modern APIs often expect JSON instead of form encoding.

const form = document.getElementById("loginForm");

form.addEventListener("submit", (e) => {
  e.preventDefault();

  const formData = new FormData(form);
  const obj = Object.fromEntries(formData.entries()); // convert to object

  fetch("/login", {
    method: "POST",
    headers: { "Content-Type": "application/json" },
    body: JSON.stringify(obj)
  })
  .then(res => res.json())
  .then(data => console.log("Response:", data));
});

This sends JSON like:

{
  "username": "john123",
  "password": "mypassword"
}

6) Manually Appending Fields

You can also build FormData by hand:

const data = new FormData();
data.append("username", "john123");
data.append("password", "mypassword");

fetch("/login", { method: "POST", body: data });

7) Server-Side Access (Examples)

  • Node.js (Express)req.body.username (with body-parser or express.urlencoded())

  • PHP$_POST['username']

  • Python (Flask)request.form['username']


8) When to Use Which Format?

Format Use Case
FormData Best for mixed data (text + file uploads).
x-www-form-urlencoded Legacy systems, traditional form processing.
JSON Modern APIs, clean structured data.

Summary:
Form data in AJAX can be sent as FormData, urlencoded, or JSON.

  • Use FormData for files or when you want easy handling.

  • Use urlencoded for compatibility with classic server-side form handlers.

  • Use JSON for modern APIs.