πŸ” AJAX Request & Response Lifecycle
Estimated reading: 4 minutes 41 views

πŸ“¨ AJAX – Send POST Request: A Complete Guide with Examples


🧲 Introduction – Why Use AJAX POST Requests?

When you need to send data to the server, such as submitting a form, uploading content, or updating a database record, the AJAX POST request is the ideal method. Unlike GET, POST does not expose data in the URL and can carry larger payloads, including files and JSON objects.

By using AJAX with POST, you can deliver a seamless user experience where forms are submitted, and content is updated without reloading the page.

🎯 In this guide, you’ll learn:

  • How to send POST requests using XMLHttpRequest and fetch()
  • How to send form data, JSON, and FormData
  • Best practices and real-world examples

πŸ” What Is an AJAX POST Request?

A POST request is an HTTP method used to send data to the server. With AJAX, this is done asynchronously, so the page doesn’t reload.

Common use cases:

  • Contact forms
  • User registration
  • File uploads
  • API data updates

🧱 AJAX POST Using XMLHttpRequest

βœ… Example – Send URL-encoded Form Data

var xhr = new XMLHttpRequest();
xhr.open("POST", "submit.php", true);
xhr.setRequestHeader("Content-Type", "application/x-www-form-urlencoded");

xhr.onreadystatechange = function () {
  if (xhr.readyState === 4 && xhr.status === 200) {
    console.log("Server response:", xhr.responseText);
  }
};

xhr.send("name=John&email=john@example.com");

πŸ” Explanation:

  • open("POST", ...) sets the method and URL
  • setRequestHeader() tells the server what type of data you’re sending
  • send() transmits the URL-encoded string

πŸ“¦ AJAX POST Using JSON Payload

var xhr = new XMLHttpRequest();
xhr.open("POST", "api/save.php", true);
xhr.setRequestHeader("Content-Type", "application/json");

xhr.onreadystatechange = function () {
  if (xhr.readyState === 4 && xhr.status === 200) {
    var result = JSON.parse(xhr.responseText);
    console.log("Message:", result.message);
  }
};

var data = JSON.stringify({ username: "john", age: 30 });
xhr.send(data);

βœ… Best for API calls and RESTful backend services.


πŸš€ AJAX POST Using fetch() API

βœ… Simple JSON POST Request with fetch

fetch("submit.php", {
  method: "POST",
  headers: {
    "Content-Type": "application/json"
  },
  body: JSON.stringify({ name: "Alice", email: "alice@example.com" })
})
  .then(res => res.json())
  .then(data => console.log("Server:", data.message))
  .catch(err => console.error("Error:", err));

βœ… Cleaner syntax, built-in Promise handling, and recommended for modern apps.


πŸ“ AJAX POST File Upload Using FormData

🧩 HTML

<form id="uploadForm">
  <input type="file" name="image" />
  <button type="submit">Upload</button>
</form>

βœ… JavaScript

document.getElementById("uploadForm").addEventListener("submit", function (e) {
  e.preventDefault();
  const formData = new FormData(this);

  fetch("upload.php", {
    method: "POST",
    body: formData
  })
    .then(res => res.text())
    .then(response => console.log("Upload result:", response));
});

βœ… You don’t need to set headersβ€”FormData handles it automatically.


πŸ“Š POST vs GET – When to Use What?

FeatureGETPOST
PurposeFetch dataSend data
Data in URLYes (query string)No (sent in body)
CachingOften cachedNot cached
Payload supportLimited (text)Large payloads (files, JSON)
VisibilityData visible in URLData hidden

⚠️ Common Mistakes to Avoid

❌ Mistakeβœ… Fix
Forgetting to set content typeUse setRequestHeader() or headers in fetch
Sending raw objects in send()Use JSON.stringify()
Manually setting headers with FormDataDon’tβ€”browser handles it automatically
Not handling server response errorsUse .catch() or check xhr.status

πŸ“Œ Summary – Recap & Takeaways

AJAX POST requests are essential for sending secure, large, and structured data to the server. Whether you’re using XMLHttpRequest or fetch(), POST allows you to build fully interactive applications with form handling, user registration, and file uploads.

πŸ” Key Takeaways:

  • Use POST to send data like JSON, form inputs, or files
  • Set headers based on the data type (application/json, multipart/form-data)
  • Prefer fetch() for modern applications
  • Handle server responses and errors gracefully

βš™οΈ Next Steps:

  • Create a form with client-side validation + AJAX POST
  • Upload multiple files using FormData.append()
  • Learn how to handle CSRF tokens in POST requests

❓ FAQs – Sending AJAX POST Requests


❓ Why use POST instead of GET in AJAX?
βœ… POST is more secure for sending sensitive data and supports larger payloads like JSON and files.


❓ Do I need to set headers manually for FormData?
❌ No. The browser sets Content-Type: multipart/form-data and boundaries automatically.


❓ How do I send JSON using POST?
βœ… Use JSON.stringify() and set Content-Type: application/json.


❓ Is it okay to use POST for fetching data?
βœ… Technically yes, but GET is the standard for data retrieval. Use POST when submitting or modifying data.


❓ Can I send multiple fields in POST?
βœ… Yes. Combine fields in an object or form and send them using JSON or FormData.


Share Now :

Leave a Reply

Your email address will not be published. Required fields are marked *

Share

AJAX – Send POST Request

Or Copy Link

CONTENTS
Scroll to Top