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

PHP AJAX Handling

AJAX lets a web page ask the server for something without reloading, like passing a note to a teacher while class goes on. PHP receives the request and sends back just the small answer.
Syntax
php
header("Content-Type: application/json");
$input = json_decode(file_get_contents("php://input"), true);   // JSON body
echo json_encode($response_data);

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
// Call `header("Content-Type: application/json")`
header("Content-Type: application/json");
// Print `json_encode(["message" => "Same script, JSON response instead of full HTML"])` to the output
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
// Call `header("Content-Type: application/json")`
header("Content-Type: application/json");
// Declare `$data` as an array: `["result" => "ok"]`
$data = ["result" => "ok"];
// Print `json_encode($data)` to the output
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
// Call `http_response_code(400)`
http_response_code(400);
// Print `json_encode(["success" => false, "error" => "Missing field"])` to the output
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
?>
Related Topics
{# common_mistakes/chapter_summary/browser_support: on Hindi pages the view already swaps in the hi_ translation fields (or blanks these out if untranslated), so this renders correctly for both languages without a lang_code check here. #}
Common Mistakes
  1. Forgetting to set the Content-Type: application/json header for JSON responses.
  2. Sending extra output such as HTML or warnings before the JSON, which breaks parsing on the client.
  3. Not checking the request method or input before using it.

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.