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

PHP AJAX Handling

What Is AJAX Handling in PHP?

When a browser sends an AJAX request, it hits a PHP script the exact same way a normal page load would -- PHP itself doesn't know the difference. The distinction is entirely about what the script sends back: instead of a full HTML page, an AJAX endpoint typically returns a small JSON payload that JavaScript on the page reads and uses to update the DOM without a reload.

Example: What Is AJAX Handling in PHP?

php
<?php
header("Content-Type: application/json");
echo json_encode(["message" => "Same script, JSON response instead of full HTML"]);
?>

Reading the Incoming Request

A form-encoded AJAX POST arrives in $_POST exactly like a regular form submission. A JSON-body AJAX request (common with fetch() sending JSON.stringify(data)) does NOT populate $_POST -- you read the raw body with file_get_contents("php://input") and decode it yourself with json_decode().

Example: Reading the Incoming Request

php
<?php
file_put_contents("php_input_sim.json", '{"name": "Alice"}');
$raw = file_get_contents("php_input_sim.json"); // stands in for php://input
$data = json_decode($raw, true);
echo $data['name'];
?>

Returning a JSON Response

Build a PHP array or object representing the result, then send it with echo json_encode($data). Setting header("Content-Type: application/json") before any output tells the browser (and the JavaScript reading the response) to parse the body as JSON rather than treat it as plain text.

Example: Returning a JSON Response

php
<?php
header("Content-Type: application/json");
$data = ["result" => "ok"];
echo json_encode($data);
?>

Signaling Success and Failure

A JSON API response commonly includes a success boolean and either a data key or an error message, so the calling JavaScript can branch cleanly. Setting the right HTTP status code with http_response_code(400) (or 404, 500, etc.) alongside the JSON body lets fetch()'s response.ok check work correctly too.

Example: Signaling Success and Failure

php
<?php
http_response_code(400);
echo json_encode(["success" => false, "error" => "Missing field"]);
?>

Contrast with a Full REST API

This single-endpoint request/response pattern is the simplest form of server communication -- a full REST API (covered in the site's dedicated REST API topics) adds resource-oriented URL design, multiple HTTP methods per resource, and consistent conventions across many endpoints. A quick AJAX handler for one page's live search or form validation doesn't need that structure.

Example: Contrast with a Full REST API

php
<?php
header("Content-Type: application/json");
echo json_encode(["success" => true, "data" => "search results"]);
// A full REST API would add multiple methods and consistent conventions across many endpoints
?>

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.