1) What is a POST Request?
-
A POST request is used to send data to the server to create or update resources.
-
Unlike GET requests, POST data is sent in the request body, not the URL.
-
Common use cases:
2) Key Features of POST Requests in AJAX
-
Data is sent in the body, which can include:
-
POST requests can change server state, unlike GET.
-
Can handle large payloads (GET URLs have length limits).
3) Sending POST with XMLHttpRequest
const xhr = new XMLHttpRequest();
xhr.open("POST", "/api/data", true);
xhr.setRequestHeader("Content-Type", "application/json");
xhr.onreadystatechange = function() {
if (xhr.readyState === 4) {
if (xhr.status === 200) {
console.log("Response:", xhr.responseText);
} else {
console.error("Error:", xhr.status);
}
}
};
const data = { name: "Alice", email: "[email protected]" };
xhr.send(JSON.stringify(data));
Notes:
4) Sending POST with Fetch API
fetch("/api/data", {
method: "POST",
headers: { "Content-Type": "application/json" },
body: JSON.stringify({ name: "Alice", email: "[email protected]" })
})
.then(res => res.json())
.then(data => console.log("Response:", data))
.catch(err => console.error("Error:", err));
Pros:
5) Sending Form Data with POST
Using FormData (for forms or files)
const form = document.getElementById("myForm");
const formData = new FormData(form);
fetch("/submit-form", {
method: "POST",
body: formData
})
.then(res => res.text())
.then(data => console.log(data))
.catch(err => console.error(err));
Notes:
6) Handling Responses and Errors
-
Check HTTP status codes (200 OK, 400 Bad Request, 500 Server Error).
-
Handle network errors via catch (Fetch) or onerror (XHR).
-
Parse the response according to its type (JSON, text, blob).
7) Security Considerations
-
Use HTTPS to encrypt sensitive POST data.
-
Protect against CSRF by including tokens in headers or body.
-
Validate/sanitize all input on the server.
8) Summary
-
POST requests are used to send data to the server via AJAX.
-
XMLHttpRequest and Fetch API are common ways to make POST calls.
-
Can send JSON, form data, or files.
-
Always handle responses, errors, and security properly.