AJAX means the browser talks to your server in the background and updates part of the page instead of reloading it. On the JavaScript side that is fetch; on the PHP side it is an ordinary script that returns JSON rather than HTML. This guide covers both halves, the error handling people skip, and the CSRF protection an AJAX endpoint still needs.
The PHP side#
<?php
// api/products.php
declare(strict_types=1);
header("Content-Type: application/json; charset=utf-8");
if ($_SERVER["REQUEST_METHOD"] !== "GET") {
http_response_code(405);
header("Allow: GET");
echo json_encode(["error" => "Method not allowed"]);
exit;
}
$max = filter_input(INPUT_GET, "max", FILTER_VALIDATE_FLOAT);
if ($max === false) {
http_response_code(400);
echo json_encode(["error" => "max must be a number"]);
exit;
}
try {
$stmt = $pdo->prepare(
"SELECT id, name, price FROM products WHERE price < ? ORDER BY name LIMIT 50"
);
$stmt->execute([$max ?? 1000]);
echo json_encode(["products" => $stmt->fetchAll()], JSON_UNESCAPED_UNICODE);
} catch (PDOException $e) {
error_log($e->getMessage());
http_response_code(500);
echo json_encode(["error" => "Could not load products"]);
}
Four habits in that file. Set the content type. Use the right status code for each outcome. Return errors as JSON, never HTML. And log the real database error while telling the client something generic — the message may contain table names or credentials.
The JavaScript side#
async function loadProducts(max) {
const response = await fetch("/api/products.php?max=" + encodeURIComponent(max));
if (!response.ok) {
const body = await response.json().catch(() => ({}));
throw new Error(body.error || "Request failed with " + response.status);
}
const data = await response.json();
return data.products;
}
try {
const products = await loadProducts(20);
render(products);
} catch (error) {
showMessage(error.message);
}
Sending data#
// JSON body
const response = await fetch("/api/orders.php", {
method: "POST",
headers: { "Content-Type": "application/json" },
body: JSON.stringify({ productId: 42, quantity: 2 }),
});
<?php
// Reading a JSON body - $_POST is empty for these
$raw = file_get_contents("php://input");
$data = json_decode($raw, true);
if (json_last_error() !== JSON_ERROR_NONE) {
http_response_code(400);
echo json_encode(["error" => "Invalid JSON"]);
exit;
}
$productId = filter_var($data["productId"] ?? null, FILTER_VALIDATE_INT);
$quantity = filter_var($data["quantity"] ?? null, FILTER_VALIDATE_INT);
if ($productId === false || $quantity === false || $quantity < 1) {
http_response_code(422);
echo json_encode(["errors" => ["quantity" => "Must be a positive whole number"]]);
exit;
}
That php://input line is the detail that catches everyone. PHP only populates $_POST for form-encoded and multipart bodies; a JSON body has to be read from the raw input stream.
Submitting a form#
const form = document.querySelector("#order-form");
form.addEventListener("submit", async (event) => {
event.preventDefault();
const button = form.querySelector("button[type=submit]");
button.disabled = true;
try {
const response = await fetch(form.action, {
method: "POST",
body: new FormData(form), // no Content-Type header - the browser sets it
});
const data = await response.json();
if (response.status === 422) {
showFieldErrors(data.errors);
return;
}
if (!response.ok) throw new Error(data.error || "Something went wrong");
showMessage("Saved");
form.reset();
} catch (error) {
showMessage(error.message);
} finally {
button.disabled = false;
}
});
With FormData, do not set the Content-Type header yourself. The browser needs to add a multipart boundary, and setting the header manually removes it, which makes PHP see an empty $_POST.
On the PHP side, form data arrives normally:
<?php
$errors = [];
$name = trim($_POST["name"] ?? "");
if ($name === "") $errors["name"] = "Name is required";
$email = filter_input(INPUT_POST, "email", FILTER_VALIDATE_EMAIL);
if ($email === false) $errors["email"] = "That does not look like an email address";
if ($errors) {
http_response_code(422);
echo json_encode(["errors" => $errors]);
exit;
}
Status codes worth using#
| Code | Meaning |
|---|---|
| 200 | fine |
| 201 | created |
| 400 | the request itself is malformed |
| 401 | not signed in |
| 403 | signed in, not allowed |
| 404 | no such thing |
| 422 | well-formed but the values fail validation |
| 500 | something broke on the server |
Distinguishing 400 from 422 is worth doing: the first means the client sent something you could not parse, the second means you parsed it and the values were wrong. The JavaScript reacts differently to each.
CSRF protection#
An AJAX endpoint that changes data needs the same protection as a form. Cookies are sent automatically, so another site can make a logged-in visitor’s browser call your endpoint.
<?php
session_start();
if (empty($_SESSION["csrf"])) {
$_SESSION["csrf"] = bin2hex(random_bytes(32));
}
?>
<meta name="csrf-token" content="<?= htmlspecialchars($_SESSION["csrf"], ENT_QUOTES) ?>">
const token = document.querySelector('meta[name="csrf-token"]').content;
await fetch("/api/orders.php", {
method: "POST",
headers: { "Content-Type": "application/json", "X-CSRF-Token": token },
body: JSON.stringify(order),
});
<?php
$sent = $_SERVER["HTTP_X_CSRF_TOKEN"] ?? "";
if (!hash_equals($_SESSION["csrf"] ?? "", $sent)) {
http_response_code(403);
echo json_encode(["error" => "Invalid request"]);
exit;
}
Use hash_equals rather than === — it compares in constant time, which removes a subtle timing attack.
File upload with progress#
fetch cannot report upload progress, so this is the one place XMLHttpRequest is still the right tool:
function upload(file, onProgress) {
return new Promise((resolve, reject) => {
const xhr = new XMLHttpRequest();
const data = new FormData();
data.append("photo", file);
xhr.upload.addEventListener("progress", (e) => {
if (e.lengthComputable) onProgress(Math.round((e.loaded / e.total) * 100));
});
xhr.addEventListener("load", () =>
xhr.status < 400 ? resolve(JSON.parse(xhr.responseText))
: reject(new Error("Upload failed")));
xhr.addEventListener("error", () => reject(new Error("Network error")));
xhr.open("POST", "/api/upload.php");
xhr.send(data);
});
}
Cancelling a request#
let controller;
async function search(term) {
controller?.abort(); // cancel the previous one
controller = new AbortController();
try {
const response = await fetch("/api/search.php?q=" + encodeURIComponent(term),
{ signal: controller.signal });
render(await response.json());
} catch (error) {
if (error.name !== "AbortError") showMessage(error.message);
}
}
Essential for search-as-you-type, where results can otherwise arrive out of order and an older response overwrites a newer one.
Questions people ask#
Do I still need jQuery for AJAX?
No. fetch is built into every current browser and returns promises, which work with async and await. jQuery’s version solved a problem that no longer exists.
Why is $_POST empty?
You sent a JSON body. PHP only fills $_POST for form-encoded and multipart requests. Read php://input and decode it yourself.
How do I debug an AJAX call?
Open the Network tab, find the request, and look at the response body. Nine times out of ten it is a PHP warning or an HTML error page where JSON was expected.
Should I return HTML or JSON?
JSON when the JavaScript decides how to display the data. An HTML fragment is a legitimate choice when the server owns the markup and you just want to swap a section of the page.
Where to go next#
- The JavaScript fetch API — the client side in depth.
- Working with APIs in PHP — calling APIs rather than serving them.
- PHP security best practices — validation and CSRF in full.