AJAX - POST requests in AJAX.

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:

    • Form submission

    • File uploads

    • Sending JSON data to an API


2) Key Features of POST Requests in AJAX

  • Data is sent in the body, which can include:

    • JSON

    • Form data (application/x-www-form-urlencoded)

    • Multipart data (for file uploads)

  • 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:

  • Content-Type specifies the format of the request body.

  • JSON is commonly used in modern APIs.


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:

  • Cleaner, promise-based syntax.

  • Handles async operations easily.


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:

  • Browser automatically sets multipart/form-data with proper boundary.

  • Ideal for file uploads and mixed fields.


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.