π¨ 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
andfetch()
- 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 URLsetRequestHeader()
tells the server what type of data you’re sendingsend()
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?
Feature | GET | POST |
---|---|---|
Purpose | Fetch data | Send data |
Data in URL | Yes (query string) | No (sent in body) |
Caching | Often cached | Not cached |
Payload support | Limited (text) | Large payloads (files, JSON) |
Visibility | Data visible in URL | Data hidden |
β οΈ Common Mistakes to Avoid
β Mistake | β Fix |
---|---|
Forgetting to set content type | Use setRequestHeader() or headers in fetch |
Sending raw objects in send() | Use JSON.stringify() |
Manually setting headers with FormData | Donβtβbrowser handles it automatically |
Not handling server response errors | Use .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 :