PHP AJAX Intro
In this page:
header("Content-Type: application/json");
echo json_encode(["key" => value]);
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.
Example: What AJAX Actually Is
<?php
// Call `header("Content-Type: application/json")`
header("Content-Type: application/json");
// Print `json_encode(["message" => "This is what a background request returns"])` to the output
echo json_encode(["message" => "This is what a background request returns"]);
?>
Login to try C/C++/Java/PHP code in the editor
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.
Example: PHP's Role as an AJAX Endpoint
<?php
// Set `$_GET['id']` to "5"
$_GET['id'] = "5";
// Print `json_encode(["id" => $_GET['id'], "processed" => true])` to the output
echo json_encode(["id" => $_GET['id'], "processed" => true]);
?>
Login to try C/C++/Java/PHP code in the editor
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.
Example: JSON: The Modern Data Format for AJAX
<?php
// Declare `$data` as an array: `["name" => "Alice", "age" => 30]`
$data = ["name" => "Alice", "age" => 30];
// Print `json_encode($data)` to the output
echo json_encode($data);
// Declare `$decoded`, set to `json_decode(json_encode($data), true)`
$decoded = json_decode(json_encode($data), true);
// Print a human-readable dump of `$decoded`
print_r($decoded);
?>
Login to try C/C++/Java/PHP code in the editor
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.
Example: A Basic AJAX Request/Response Cycle
<?php
// Call `header("Content-Type: application/json")`
header("Content-Type: application/json");
// Print `json_encode(["status" => "ok", "message" => "Received by fetch(), consumed in .then()"])` to the output
echo json_encode(["status" => "ok", "message" => "Received by fetch(), consumed in .then()"]);
?>
Login to try C/C++/Java/PHP code in the editor
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.
Example: Why AJAX Matters for User Experience
<?php
// Check whether `!function_exists('str_starts_with')`
if (!function_exists('str_starts_with')) {
// Define the function `str_starts_with` taking `$haystack`, `$needle`
function str_starts_with($haystack, $needle) { return substr($haystack, 0, strlen($needle)) === $needle; }
}
// Set `$_GET['query']` to "ph"
$_GET['query'] = "ph";
// Declare `$suggestions` as an array: `["php", "phpunit", "phpmailer"]`
$suggestions = ["php", "phpunit", "phpmailer"];
// Declare `$matches`, set to `array_filter($suggestions, function ($s) { return str_starts_with($s, $_GET['query']); })`
$matches = array_filter($suggestions, function ($s) { return str_starts_with($s, $_GET['query']); });
// Print `json_encode(array_values($matches))` to the output
echo json_encode(array_values($matches));
?>
Login to try C/C++/Java/PHP code in the editor
- 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.
- Forgetting that the "XML" in AJAX is largely historical -- modern AJAX requests almost always exchange JSON, not actual XML documents.
- 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.
- 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.
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.
Chapter Quiz — Complete all 12 topics to unlock
0/12 topics done
Complete these topics first: