AJAX Explained: Updating Pages Without a Reload Using Fetch and PHP
What is AJAX?
AJAX (Asynchronous JavaScript and XML) is a technique for exchanging data with a server in the background and updating part of a web page without reloading it. Despite the name, modern AJAX usually uses the Fetch API and JSON rather than XML. Typical uses include live search, form submission, loading more results and saving changes as you edit.
How AJAX works and the terms involved
In a traditional page, every form submission or link click asks the server for a whole new HTML document. With AJAX, JavaScript sends a smaller request, the server returns just the data or fragment needed, and the script updates the relevant part of the DOM.
- An event happens, such as a form
submitor a button click. - JavaScript sends an asynchronous HTTP request, usually with
fetch(). - A server endpoint, for example a PHP script, validates the input and responds, typically with JSON.
- JavaScript checks the response and updates the page, while the visitor keeps using it.
| Term | Meaning |
|---|---|
| Endpoint | A URL on the server that accepts requests and returns data |
| XMLHttpRequest | The original browser API for AJAX, still supported |
| Fetch API | The modern, promise-based replacement for XMLHttpRequest |
| Progressive enhancement | Building a working HTML version first, then adding JavaScript on top |
| CSRF token | A secret value proving a request came from your own page |
AJAX suits small, frequent interactions where a full reload would feel slow or lose the visitor's place, such as filtering a list, adding to a cart or validating a username. It is not needed for every link: ordinary navigation between pages is simpler, works with the back button and is easier for search engines to follow. If you do update large parts of the page, consider updating the URL with history.pushState() so the result can be bookmarked and shared.
Building the server side: a PHP endpoint
This endpoint saves a newsletter sign-up. It accepts both a normal form post and an AJAX request, checks a CSRF token, validates the email and responds in the format the client asked for. It assumes a session was started on the page that showed the form.
<?php
// subscribe.php
declare(strict_types=1);
session_start();
$wantsJson = str_contains($_SERVER['HTTP_ACCEPT'] ?? '', 'application/json');
function respond(int $status, array $body, bool $json): never
{
http_response_code($status);
if ($json) {
header('Content-Type: application/json; charset=utf-8');
echo json_encode($body, JSON_THROW_ON_ERROR);
} else {
$_SESSION['flash'] = $body['message'];
header('Location: /newsletter.php', true, 303);
}
exit;
}
if ($_SERVER['REQUEST_METHOD'] !== 'POST') {
respond(405, ['ok' => false, 'message' => 'Method not allowed'], $wantsJson);
}
$expected = $_SESSION['csrf_token'] ?? '';
$token = $_SERVER['HTTP_X_CSRF_TOKEN'] ?? $_POST['csrf_token'] ?? '';
if ($expected === '' || !is_string($token) || !hash_equals($expected, $token)) {
respond(403, ['ok' => false, 'message' => 'Your session expired. Please reload the page.'], $wantsJson);
}
$email = filter_var(trim($_POST['email'] ?? ''), FILTER_VALIDATE_EMAIL);
if ($email === false) {
respond(422, ['ok' => false, 'message' => 'Please enter a valid email address.'], $wantsJson);
}
// Save with a prepared statement here (see the PDO examples in the MySQL guide)
respond(200, ['ok' => true, 'message' => 'Thanks, you are subscribed.'], $wantsJson);Use meaningful status codes: 422 for validation errors, 403 for a failed token and 200 for success. Escape output and use prepared statements exactly as you would for any other request; the secure PHP guide covers both.
Progressive enhancement: start with a working form
Write the form so it works with no JavaScript at all: a real action, method="post" and a submit button. JavaScript then intercepts the submit and sends the same data with fetch. If the script fails to load, or a request runs into trouble on a slow connection, the visitor still has a working form.
<?php
// newsletter.php (top of the page)
session_start();
$_SESSION['csrf_token'] ??= bin2hex(random_bytes(32));
$token = htmlspecialchars($_SESSION['csrf_token'], ENT_QUOTES, 'UTF-8');
?>
<meta name="csrf-token" content="<?= $token ?>">
<form id="subscribe" action="/subscribe.php" method="post">
<input type="hidden" name="csrf_token" value="<?= $token ?>">
<label for="email">Email</label>
<input id="email" name="email" type="email" required autocomplete="email">
<button type="submit">Subscribe</button>
<p id="status" role="status"></p>
</form>
<script src="/js/subscribe.js" defer></script>The hidden field covers the no-JavaScript path, and the meta tag gives scripts on any page easy access to the token. The role="status" paragraph announces results to screen reader users without moving their focus.
Building the client side with fetch
// js/subscribe.js
const form = document.querySelector('#subscribe');
const status = document.querySelector('#status');
const token = document.querySelector('meta[name="csrf-token"]').content;
form.addEventListener('submit', async event => {
event.preventDefault();
const button = form.querySelector('button');
button.disabled = true;
status.textContent = 'Sending...';
try {
const response = await fetch(form.action, {
method: 'POST',
headers: { Accept: 'application/json', 'X-CSRF-Token': token },
body: new FormData(form),
signal: AbortSignal.timeout(10000),
});
const result = await response.json();
status.textContent = result.message;
if (response.ok) form.reset();
} catch (error) {
status.textContent = 'Something went wrong. Please try again.';
} finally {
button.disabled = false;
}
});Sending FormData means PHP reads the fields from $_POST exactly as it would for a normal submission, so the endpoint needs no separate JSON parsing. Disabling the button prevents duplicate submissions while the request is in flight, and the status text tells every visitor, including screen reader users, what happened. The same pattern works for any form: only the endpoint and the success handling change. Error handling here follows the patterns in our async/await guide.
CSRF protection for AJAX requests
Cross-site request forgery (CSRF) tricks a logged-in visitor's browser into sending a request to your site from another site, carrying their session cookie. Any request that changes data needs protection, whether it comes from a form or from fetch.
- Generate a random token per session with
random_bytes()and store it in$_SESSION. - Send it with each state-changing request, in a hidden field or a custom header such as
X-CSRF-Token. - Compare it on the server with
hash_equals(), which runs in constant time. - Set session cookies with
SameSite=LaxorStrict,HttpOnlyandSecureas a further layer, as explained in the sessions and cookies guide. - Never change data on a
GETrequest, because links and images can trigger GET requests from anywhere.
Practical exercise: a "load more" button with a fallback
Build a blog list that shows ten posts and a "Load more" link to ?page=2.
- Make the link work without JavaScript, rendering the next page on the server.
- Add a
posts.phpendpoint that returns the next ten posts as JSON when theAcceptheader asks for it. - Intercept the link click, fetch the next page, append posts with
createElementand update the link to the following page. - Hide the link when the endpoint reports there are no more posts.
- Add a "like" button on each post that sends a POST with a CSRF token and shows the new count.
You are done when the list works with JavaScript disabled, likes are rejected without a valid token, and the status messages are announced by a screen reader. Projects like this, combining PHP endpoints and front-end scripts, form part of SkillNewton's advanced PHP course.
Common mistakes
- Building an AJAX-only form that does nothing when JavaScript fails to load.
- Skipping CSRF checks on endpoints because "only our JavaScript calls them".
- Trusting client-side validation and not validating again in PHP.
- Returning status 200 with an error message, so the client cannot tell success from failure.
- Inserting server responses with
innerHTML, which opens the page to cross-site scripting.
Frequently asked questions
Is AJAX still used?
Yes, constantly, although the word is used less. Every fetch call that updates part of a page without a reload is AJAX, including those inside frameworks.
Do I need jQuery for AJAX?
No. The built-in Fetch API covers what $.ajax() used to provide. jQuery is still found in older projects and some WordPress themes.
Does AJAX content hurt SEO?
Content loaded only after a click may not be seen by search engines. Keep important content in the initial HTML and use real links with URLs, as the progressive enhancement approach in this guide does.
Should an AJAX endpoint return HTML or JSON?
Either can work. JSON keeps data and presentation separate and suits APIs, while returning a small HTML fragment rendered by PHP can reuse your existing templates. Escape data properly in both cases.