← Back to PHP Course | Chapter 15: Web Development | Lesson 8 of 12

PHP AJAX Intro

A normal web page reloads entirely every time it needs new data from the server -- a jarring, slow experience for something as small as updating a notification count. AJAX (Asynchronous JavaScript and XML) lets a page send a request to the server and receive data back in the background, updating just part of the page without a full reload.

What AJAX Actually Is

AJAX is not a single technology, but a technique: JavaScript in the browser sends an HTTP request to a server in the background (without navigating away from the current page), and when the response comes back, JavaScript updates just the relevant part of the page's content.

Note: Think of AJAX as "a normal HTTP request, triggered by JavaScript instead of by clicking a link", since that reframes it as something you already understand from regular page requests.

Warning: An AJAX request still goes to a real server endpoint over HTTP -- it is not magic, and that endpoint needs to actually exist and handle the request correctly, exactly like any normal page.

Example: What AJAX Actually Is

php
<?php
header("Content-Type: application/json");
echo json_encode(["message" => "This is what a background request returns"]);
?>

PHP's Role as an AJAX Endpoint

From PHP's perspective, handling an AJAX request looks almost identical to handling a normal page request -- it receives an HTTP request (often with $_GET or $_POST data), processes it, and sends back a response. The only real difference is that the response is usually consumed by JavaScript rather than rendered as a full HTML page.

Note: Structure a PHP AJAX endpoint just like any other script: read the request, do the work, send the response -- no special AJAX-specific PHP syntax exists.

Warning: An AJAX endpoint that accidentally outputs extra content (like a stray warning or notice) before its intended response can corrupt the data the JavaScript is expecting to parse.

Example: PHP's Role as an AJAX Endpoint

php
<?php
$_GET['id'] = "5";
echo json_encode(["id" => $_GET['id'], "processed" => true]);
?>

JSON: The Modern Data Format for AJAX

Despite AJAX's name referencing XML, modern AJAX requests overwhelmingly exchange JSON instead -- it is more compact, maps naturally onto JavaScript objects and arrays, and PHP has built-in json_encode() and json_decode() functions making it trivial to produce and consume.

Note: Default to JSON for any new AJAX endpoint you build; reserve actual XML for situations specifically requiring it, like integrating with a legacy system.

Warning: Forgetting to set the Content-Type: application/json response header does not break JSON parsing in most JavaScript fetch code, but it is still good practice for correctness and for tools that inspect the response.

Example: JSON: The Modern Data Format for AJAX

php
<?php
$data = ["name" => "Alice", "age" => 30];
echo json_encode($data);
$decoded = json_decode(json_encode($data), true);
print_r($decoded);
?>

A Basic AJAX Request/Response Cycle

Putting it together end to end: JavaScript's fetch() sends a request to a PHP endpoint, that PHP script processes the request and outputs a response (usually JSON), and the JavaScript's .then() callback receives and uses that response to update the page.

Note: Test a new AJAX endpoint by visiting its URL directly in the browser first (for a GET endpoint), confirming it returns exactly the expected response before wiring up the JavaScript side.

Warning: A PHP endpoint that produces an unhandled error returns an HTML error page as its response body, which will fail when the JavaScript tries to parse it as JSON.

Example: A Basic AJAX Request/Response Cycle

php
<?php
header("Content-Type: application/json");
echo json_encode(["status" => "ok", "message" => "Received by fetch(), consumed in .then()"]);
?>

Why AJAX Matters for User Experience

AJAX enables the responsive, app-like interactions users now expect from the web -- live search suggestions as you type, a "like" button that updates instantly, form validation that shows errors without reloading -- all things a traditional full-page-reload model handles clumsily by comparison.

Note: Reach for AJAX specifically for interactions that genuinely benefit from feeling instant and partial, rather than converting every single page interaction into an AJAX call unnecessarily.

Warning: An AJAX-heavy page still needs to work reasonably (or degrade gracefully) if JavaScript fails to load or is disabled, depending on how critical the AJAX-driven functionality is.

Example: Why AJAX Matters for User Experience

php
<?php
if (!function_exists('str_starts_with')) {
    function str_starts_with($haystack, $needle) { return substr($haystack, 0, strlen($needle)) === $needle; }
}
$_GET['query'] = "ph";
$suggestions = ["php", "phpunit", "phpmailer"];
$matches = array_filter($suggestions, function ($s) { return str_starts_with($s, $_GET['query']); });
echo json_encode(array_values($matches));
?>
Common Mistakes
  1. Confusing AJAX with a specific technology -- it is a technique combining JavaScript's fetch/XMLHttpRequest with a server endpoint, not a library or a language feature by itself.
  2. Forgetting that the "XML" in AJAX is largely historical -- modern AJAX requests almost always exchange JSON, not actual XML documents.
  3. Assuming an AJAX request automatically has access to the same PHP session as the page that triggered it, without confirming cookies/session handling are configured correctly.
Chapter Summary
  • AJAX lets JavaScript in the browser send a request to a server endpoint and receive a response, without reloading the whole page.
  • PHP's role in AJAX is simply being a normal server endpoint -- it receives the request, processes it, and sends back a response, just like it would for a regular page load.
  • Modern AJAX overwhelmingly exchanges JSON data rather than actual XML, despite the name's historical origin.
Browser Support

AJAX-style requests are supported in every modern browser via the fetch API or XMLHttpRequest; PHP's role as a server endpoint works identically to serving a normal page.

Login to run this code

C/C++/Java/PHP execution requires a free account. Your code is saved — you'll land right back in the editor after logging in.