How do you send HTTP POST requests using XMLHttpRequest in JavaScript? | A1Lab@FahadM to JavaScriptEnglish • 4 days ago

How do you send HTTP POST requests using XMLHttpRequest in JavaScript?

message-square
0

To send an HTTP POST request with XMLHttpRequest in JavaScript, guard window.XMLHttpRequest and validate inputs first, instantiate const xhr = new XMLHttpRequest(), call xhr.open("POST", url, true), set headers such as Content-Type: application/json (or let the browser set multipart/form-data automatically for FormData), attach onload, onerror, ontimeout, and onabort handlers, and send a serialized payload (without mutating the caller’s object) via xhr.send(body). In modern codebases, fetch() is often preferred, but wrapping XMLHttpRequest in a Promise remains useful when you need upload progress events (xhr.upload.onprogress) or older XHR APIs.


1. Sending a JSON POST Request with XMLHttpRequest Wrapped in a Promise

Validate the URL and payload, serialize objects to JSON without mutating them, set Content-Type: application/json after xhr.open(), and handle HTTP status codes, timeouts, and network failures cleanly:

// Send an HTTP POST request via XMLHttpRequest with explicit guards and timeout safety
function postJsonWithXhr(url, payload = {}, { timeoutMs = 10000, headers = {} } = {}) {
  if (typeof window === "undefined" || typeof window.XMLHttpRequest !== "function") {
    return Promise.reject(new Error("XMLHttpRequest is not available in this environment."));
  }

  if (typeof url !== "string" || url.trim() === "") {
    return Promise.reject(new TypeError("Expected a non-empty target URL."));
  }

  if (typeof timeoutMs !== "number" || !Number.isFinite(timeoutMs) || timeoutMs < 0) {
    return Promise.reject(new RangeError("Expected timeoutMs to be a non-negative finite number."));
  }

  let serializedBody;
  try {
    serializedBody = typeof payload === "string" ? payload : JSON.stringify(payload ?? {});
  } catch (err) {
    return Promise.reject(
      new Error(`Failed to serialize POST payload: ${err && err.message ? err.message : String(err)}`)
    );
  }

  return new Promise((resolve, reject) => {
    const xhr = new window.XMLHttpRequest();
    xhr.open("POST", url.trim(), true);
    xhr.timeout = timeoutMs;
    xhr.setRequestHeader("Content-Type", "application/json; charset=UTF-8");

    if (headers && typeof headers === "object") {
      for (const [key, value] of Object.entries(headers)) {
        if (typeof key === "string" && key.trim() !== "" && typeof value === "string") {
          xhr.setRequestHeader(key.trim(), value);
        }
      }
    }

    xhr.onload = () => {
      const isSuccess = xhr.status >= 200 && xhr.status < 300;
      const rawText = xhr.responseText;

      if (!isSuccess) {
        reject(new Error(`POST "${url}" failed with HTTP ${xhr.status} (${xhr.statusText || "Error"})`));
        return;
      }

      try {
        const parsed = rawText ? JSON.parse(rawText) : null;
        resolve({ status: xhr.status, data: parsed, rawText });
      } catch {
        resolve({ status: xhr.status, data: rawText, rawText });
      }
    };

    xhr.onerror = () => {
      reject(new Error(`Network error while sending POST request to "${url}".`));
    };

    xhr.ontimeout = () => {
      reject(new Error(`POST request to "${url}" timed out after ${timeoutMs}ms.`));
    };

    xhr.onabort = () => {
      reject(new Error(`POST request to "${url}" was aborted.`));
    };

    xhr.send(serializedBody);
  });
}

// Example usage:
// postJsonWithXhr("/api/items", { title: "New item", active: true })
//   .then((res) => console.log("Created:", res.data))
//   .catch((err) => console.error(err.message));
  • Headers after .open(): Calling xhr.setRequestHeader() before xhr.open() throws an InvalidStateError—setting it after .open() and before .send() guarantees valid state.
  • Explicit status & timeout checks: Treats non-2xx HTTP statuses as errors rather than silently resolving 400/500 responses as success.

2. Sending FormData or URL-Encoded Forms with XMLHttpRequest

When sending multipart file uploads (FormData) or application/x-www-form-urlencoded payloads, pass the FormData or URLSearchParams instance directly to xhr.send() and do not manually force Content-Type: application/json:

// Send FormData or URLSearchParams via XMLHttpRequest without overriding multipart boundaries
function postFormWithXhr(url, formPayload, { timeoutMs = 15000, onProgress = null } = {}) {
  if (typeof window === "undefined" || typeof window.XMLHttpRequest !== "function") {
    return Promise.reject(new Error("XMLHttpRequest is not available in this environment."));
  }

  if (typeof url !== "string" || url.trim() === "") {
    return Promise.reject(new TypeError("Expected a non-empty target URL."));
  }

  const isFormData = typeof FormData !== "undefined" && formPayload instanceof FormData;
  const isUrlSearchParams =
    typeof URLSearchParams !== "undefined" && formPayload instanceof URLSearchParams;

  if (!isFormData && !isUrlSearchParams && typeof formPayload !== "string") {
    return Promise.reject(
      new TypeError("Expected formPayload to be a FormData, URLSearchParams, or encoded string.")
    );
  }

  return new Promise((resolve, reject) => {
    const xhr = new window.XMLHttpRequest();
    xhr.open("POST", url.trim(), true);
    xhr.timeout = timeoutMs;

    if (isUrlSearchParams) {
      xhr.setRequestHeader("Content-Type", "application/x-www-form-urlencoded; charset=UTF-8");
    }

    if (typeof onProgress === "function" && xhr.upload) {
      xhr.upload.onprogress = (event) => {
        if (event.lengthComputable && event.total > 0) {
          const percent = Math.round((event.loaded / event.total) * 100);
          onProgress({ loaded: event.loaded, total: event.total, percent });
        }
      };
    }

    xhr.onload = () => {
      if (xhr.status >= 200 && xhr.status < 300) {
        resolve({ status: xhr.status, responseText: xhr.responseText });
      } else {
        reject(new Error(`Form POST failed with HTTP ${xhr.status}.`));
      }
    };

    xhr.onerror = () => reject(new Error("Network error during form upload."));
    xhr.ontimeout = () => reject(new Error(`Form POST timed out after ${timeoutMs}ms.`));

    xhr.send(isUrlSearchParams ? formPayload.toString() : formPayload);
  });
}

// Example usage:
// const fd = new FormData();
// fd.append("name", "report.pdf");
// postFormWithXhr("/api/upload", fd, { onProgress: ({ percent }) => console.log(`${percent}%`) });
  • Automatic boundary for FormData: Letting the browser set Content-Type on FormData ensures the multipart/form-data; boundary=... header matches the body.
  • Upload progress tracking: xhr.upload.onprogress gives real-time byte/percentage updates during large uploads.

3. Common Traps to Avoid

Sending HTTP POST requests with XMLHttpRequest often runs into a few pitfalls:

  • Passing a raw JS object directly to xhr.send(obj) expecting JSON: xhr.send({ a: 1 }) converts the object to "[object Object]"—always JSON.stringify(obj) first and set Content-Type: application/json.
  • Calling xhr.setRequestHeader() before xhr.open(): Calling setRequestHeader() before .open() throws DOMException: Failed to execute 'setRequestHeader' on 'XMLHttpRequest': The object's state must be OPENED.
  • Setting a manual Content-Type: multipart/form-data header on FormData: Overriding Content-Type manually strips the generated boundary parameter and causes server multipart parsers to fail.

TL;DR: Call xhr.open("POST", url, true), set headers like Content-Type: application/json after .open(), wire onload, onerror, and ontimeout (checking xhr.status is 2xx), and pass a serialized string, URLSearchParams, or FormData to xhr.send(body).