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

PHP AJAX PHP

Beyond a minimal single-value response, a real PHP AJAX endpoint typically needs to read incoming request data, validate it, do some actual processing, and return a structured response -- following consistent patterns for handling both GET and POST-based AJAX requests reliably.

Reading GET-Based AJAX Requests

When JavaScript sends an AJAX request via a GET method (often with query parameters appended to the URL), the PHP endpoint reads that data the exact same way it would for a normal page: through the $_GET superglobal.

Note: Use GET-based AJAX requests for read-only operations that fetch data without changing anything on the server, matching the semantic meaning of the GET method.

Warning: GET request data is visible in the URL and browser history -- avoid sending sensitive information (like a password) via a GET-based AJAX request.

Example: Reading GET-Based AJAX Requests

php
<?php
$_GET['search'] = "php";
echo json_encode(["query" => $_GET['search']]);
?>

Reading POST-Based AJAX Requests

AJAX requests sent with the POST method carry their data in the request body rather than the URL, and PHP reads them through the familiar $_POST superglobal -- appropriate for AJAX actions that create, update, or delete something on the server, matching POST's semantic meaning.

Note: Use POST-based AJAX for any action that changes server-side state (creating, updating, deleting), reserving GET for read-only data fetches.

Warning: A POST-based AJAX request from JavaScript must explicitly set its method to "POST" and typically also set the appropriate Content-Type header, or PHP may not populate $_POST as expected.

Example: Reading POST-Based AJAX Requests

php
<?php
$_POST['title'] = "New Post";
echo json_encode(["created" => $_POST['title']]);
?>

Validating AJAX Request Data

Data arriving through an AJAX request deserves exactly the same validation as data from a regular HTML form -- checking required fields are present, values are the expected type and format, and returning a clear error response when something does not pass, rather than silently proceeding with bad data.

Note: Reuse the same validation functions and rules for AJAX endpoints that you use for regular form submissions, rather than writing separate, duplicated validation logic.

Warning: Skipping validation on an AJAX endpoint because "it is called from our own JavaScript" ignores that any endpoint can be called directly, bypassing the JavaScript entirely.

Example: Validating AJAX Request Data

php
<?php
$_POST['email'] = "not-an-email";
if (!filter_var($_POST['email'], FILTER_VALIDATE_EMAIL)) {
    http_response_code(400);
    echo json_encode(["status" => "error", "message" => "Invalid email"]);
}
?>

Returning Structured JSON Responses

A consistent response shape -- like always including a "status" field ("ok" or "error"), and optionally a "message" or "data" field -- makes the JavaScript side's handling code simpler and more predictable, since it always knows what shape of object to expect back.

Note: Pick one consistent response structure (a status field plus data/message) and use it across every AJAX endpoint in a project, rather than a different shape per endpoint.

Warning: An endpoint that sometimes returns a plain string and other times a JSON object (depending on success or failure) forces the JavaScript to guess which format it received.

Example: Returning Structured JSON Responses

php
<?php
echo json_encode(["status" => "ok", "data" => ["id" => 1]]);
?>

Handling Errors Gracefully in AJAX Endpoints

An AJAX endpoint should catch and report its own errors as a well-formed response (with an appropriate HTTP status code), rather than letting a raw PHP error or warning leak into the response body, which would break the JavaScript trying to parse it as JSON.

Note: Set an appropriate HTTP status code (like 400 for bad input, 500 for a server error) alongside a JSON error body, so both the status code and the message clearly communicate what went wrong.

Warning: An uncaught PHP error inside an AJAX endpoint typically outputs an HTML error page as the response, which will fail when JavaScript tries to parse it with response.json().

Example: Handling Errors Gracefully in AJAX Endpoints

php
<?php
try {
    throw new Exception("Something failed");
} catch (Exception $e) {
    http_response_code(500);
    echo json_encode(["status" => "error", "message" => "Something went wrong"]);
}
?>
Common Mistakes
  1. Not distinguishing between GET-style AJAX requests (read via $_GET) and POST-style ones (read via $_POST), and reading from the wrong superglobal for how the request was actually made.
  2. Skipping validation on AJAX-submitted data just because it came from JavaScript instead of a regular form -- it is still untrusted user input and needs the same scrutiny.
  3. Returning inconsistent response shapes from the same endpoint (sometimes a plain string, sometimes JSON) depending on the code path, making the JavaScript side harder to write reliably.
Chapter Summary
  • A PHP AJAX endpoint reads request data from $_GET or $_POST exactly like any other PHP script.
  • Validating and sanitizing AJAX request data is just as important as for a regular form submission, since it is equally untrusted.
  • Keeping a consistent response format (like always returning JSON with a "status" field) makes the corresponding JavaScript code simpler and more predictable.
Browser Support

Reading $_GET/$_POST and producing a response works identically whether a PHP script is serving a full page or an AJAX endpoint.

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.