AJAX Request
An AJAX request is an HTTP request fired from JavaScript. Method, URL, headers, and body decide what the server will do.
Anatomy
| Piece | Where |
|---|---|
| HTTP method | GET, POST, PUT, PATCH, DELETE |
| URL | The endpoint plus query string |
| Headers | Content-Type, Accept, Authorization, custom X-… |
| Body | JSON, FormData, raw text, Blob |
| Credentials | Cookies (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' });
Three concatenated words.
Discussion
Loading…