PHP AJAX PHP
In this page:
$value = $_GET["key"] ?? ""; // GET request
$value = $_POST["key"] ?? ""; // POST request
if ($value === "") {
http_response_code(400); // validate before using
}
echo json_encode($response_data);
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.
Example: Reading GET-Based AJAX Requests
<?php
// Set `$_GET['search']` to "php"
$_GET['search'] = "php";
// Print `json_encode(["query" => $_GET['search']])` to the output
echo json_encode(["query" => $_GET['search']]);
?>
Login to try C/C++/Java/PHP code in the editor
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.
Example: Reading POST-Based AJAX Requests
<?php
// Set `$_POST['title']` to "New Post"
$_POST['title'] = "New Post";
// Print `json_encode(["created" => $_POST['title']])` to the output
echo json_encode(["created" => $_POST['title']]);
?>
Login to try C/C++/Java/PHP code in the editor
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.
Example: Validating AJAX Request Data
<?php
// Set `$_POST['email']` to "not-an-email"
$_POST['email'] = "not-an-email";
// Check whether `!filter_var($_POST['email'], FILTER_VALIDATE_EMAIL)`
if (!filter_var($_POST['email'], FILTER_VALIDATE_EMAIL)) {
// Call `http_response_code(400)`
http_response_code(400);
// Print `json_encode(["status" => "error", "message" => "Invalid email"])` to the output
echo json_encode(["status" => "error", "message" => "Invalid email"]);
}
?>
Login to try C/C++/Java/PHP code in the editor
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.
Example: Returning Structured JSON Responses
<?php
// Print `json_encode(["status" => "ok", "data" => ["id" => 1]])` to the output
echo json_encode(["status" => "ok", "data" => ["id" => 1]]);
?>
Login to try C/C++/Java/PHP code in the editor
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.
Example: Handling Errors Gracefully in AJAX Endpoints
<?php
// Try running this block; jump to `catch` if it throws
try {
// Throw a new `Exception` with message "Something failed"
throw new Exception("Something failed");
// Catch Exception $e
} catch (Exception $e) {
// Call `http_response_code(500)`
http_response_code(500);
// Print `json_encode(["status" => "error", "message" => "Something went wrong"])` to the output
echo json_encode(["status" => "error", "message" => "Something went wrong"]);
}
?>
Login to try C/C++/Java/PHP code in the editor
- 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.
- 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.
- 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.
- 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.
Reading $_GET/$_POST and producing a response works identically whether a PHP script is serving a full page or an AJAX endpoint.
Chapter Quiz — Complete all 12 topics to unlock
0/12 topics done
Complete these topics first: