iwantcoding.com
🔥 Daily 👥 Rooms 🏆 Top Log in Sign up

AJAX Request

An AJAX request is an HTTP request fired from JavaScript. Method, URL, headers, and body decide what the server will do.

Anatomy

PieceWhere
HTTP methodGET, POST, PUT, PATCH, DELETE
URLThe endpoint plus query string
HeadersContent-Type, Accept, Authorization, custom X-…
BodyJSON, FormData, raw text, Blob
CredentialsCookies (only if credentials: "include" or same-origin)

The four common shapes

JS — GET with query
const params = new URLSearchParams({ page: 2, q: "ada" });
const res = await fetch(`/api/users?${params}`);
const list = await res.json();
JS — JSON POST
const res = await fetch("/api/users", {
  method: "POST",
  headers: { "Content-Type": "application/json" },
  body: JSON.stringify({ name: "Ada", role: "admin" }),
});
JS — File upload (multipart)
const fd = new FormData();
fd.append("avatar", fileInput.files[0]);
fd.append("name", "Ada");
await fetch("/api/users", { method: "POST", body: fd });   // no Content-Type — browser sets it with boundary
JS — DELETE with auth
await fetch(`/api/users/${id}`, {
  method: "DELETE",
  headers: { "Authorization": `Bearer ${token}` },
});

CORS in one paragraph

A request to a different origin requires the server to send Access-Control-Allow-Origin. Anything beyond simple GETs triggers a "preflight" OPTIONS request. The browser blocks the response if the headers don't permit it — it's a browser rule; the server still receives the request.

Tip: Wrap your fetch calls in a small helper that adds the base URL, headers, JSON encoding, and error throwing on non-2xx. Saves the same six lines in every call.

Example

Example
<!DOCTYPE html>
<html>
<body>

<p id="out"></p>

<script>
document.getElementById("out").textContent = "Hello from AJAX Request!";
</script>

</body>
</html>
Try it Yourself »

Exercise

Build a query string for a GET.

const params = new ({ page: 2, q: 'ada' });

Test yourself

Q1. For a POST with a JSON body you must set…
Q2. For multipart file uploads…
Q3. CORS preflight requests use which method?

Discussion

Loading…