← Back to JavaScript Course | Chapter 9: Async & Web APIs | Lesson 16 of 26

JS AJAX PHP

PHP is one of the most common server-side languages paired with AJAX requests -- a JavaScript fetch call on the client side, and a PHP script on the server reading the request, processing it, and returning a response, is a pattern found across an enormous number of existing websites.

A Basic Fetch-to-PHP Round Trip

JavaScript's fetch() sends a request to a .php file's URL exactly like it would to any other endpoint, and the PHP script processes it and echoes back a response, which the JavaScript then reads -- there is nothing PHP-specific about the client-side code at all.

Note: Test a new PHP endpoint directly in the browser (or with curl) first, confirming its output before wiring up the JavaScript fetch call.

Warning: A PHP script that outputs anything extra (like a stray warning) before its intended response corrupts the response body the JavaScript is expecting to read.

Example: A Basic Fetch-to-PHP Round Trip

javascript
fetch("greet.php")
  .then(response => response.text())
  .then(text => console.log(text)); // PHP echoes a response back

Returning JSON from PHP for JavaScript

A PHP endpoint returns data JavaScript can parse structurally by setting header('Content-Type: application/json') and echoing the result of json_encode() on a PHP array or object -- the JavaScript side then simply calls response.json() to get back a usable JavaScript value.

Note: Always set the JSON content type header on the PHP side, even though most fetch code will still technically parse JSON without it -- it is correct and expected practice.

Warning: Forgetting json_encode() and echoing a raw PHP array directly outputs the text "Array" instead of actual JSON, which response.json() cannot parse.

Example: Returning JSON from PHP for JavaScript

javascript
fetch("data.php")
  .then(response => response.json())
  .then(data => console.log(data));

Sending POST Data to PHP

A POST request from JavaScript can send its data as form-encoded (the traditional format PHP's $_POST reads automatically) or as a JSON body (which PHP must read manually via php://input) -- both work, but form-encoding requires the least additional PHP code.

Note: Use form-encoded body content (matching Content-Type: application/x-www-form-urlencoded) when you specifically want $_POST populated automatically without extra parsing code.

Warning: Sending a JSON body to a plain PHP script expecting form data leaves $_POST empty, since PHP does not automatically parse a JSON body into $_POST the way it does form-encoded data.

Example: Sending POST Data to PHP

javascript
const formData = new FormData();
formData.append("name", "Sam");
fetch("save.php", { method: "POST", body: formData }).then(r => r.json()).then(data => console.log(data));

Sending JSON to PHP

When the request body is JSON instead of form-encoded, PHP must read it manually: file_get_contents('php://input') retrieves the raw request body, and json_decode() converts it into a PHP array or object, since $_POST stays empty for a JSON-formatted body.

Note: Use json_decode(file_get_contents('php://input'), true) as the standard pattern to read a JSON request body on the PHP side.

Warning: Forgetting the true second argument to json_decode() returns a PHP object instead of an associative array, which changes whether you access fields with -> or [].

Example: Sending JSON to PHP

javascript
fetch("save.php", {
  method: "POST",
  headers: { "Content-Type": "application/json" },
  body: JSON.stringify({ name: "Sam" }),
}).then(r => r.json()).then(data => console.log(data));

Validating Data on the PHP Side

Just like a regular form submission, any data arriving from an AJAX request needs server-side validation before being trusted or stored -- checking required fields, correct formats, and appropriate types, and returning a clear JSON error response when validation fails.

Note: Reuse the exact same PHP validation functions and rules for AJAX endpoints that you already use for regular form submissions.

Warning: Trusting AJAX-submitted data as inherently safer than form data (since it "came from your own JavaScript") ignores that any endpoint can be called directly, bypassing the JavaScript entirely.

Example: Validating Data on the PHP Side

javascript
fetch("register.php", {
  method: "POST",
  headers: { "Content-Type": "application/json" },
  body: JSON.stringify({ email: "" }),
})
  .then(r => r.json())
  .then(data => console.log(data.error));
Common Mistakes
  1. Assuming a PHP endpoint automatically returns JSON without explicitly setting the Content-Type: application/json header and calling json_encode() on the response data.
  2. Forgetting that a PHP script reads GET data via $_GET and POST data via $_POST -- sending data with the wrong method leaves the PHP script looking in the wrong place.
  3. Not validating or sanitizing data sent from JavaScript on the PHP side, since client-side data is exactly as untrustworthy coming from AJAX as from a regular HTML form.
Chapter Summary
  • A PHP AJAX endpoint reads incoming data from $_GET or $_POST, exactly like it would for a regular page request.
  • json_encode() on the PHP side converts a PHP array or object into a JSON string the JavaScript fetch call can parse with response.json().
  • Data sent from JavaScript to PHP is just as untrusted as data from a regular form, and needs the same validation and sanitization.
Browser Support

AJAX requests work identically with a PHP backend as with any other server-side language, since the browser side is entirely language-agnostic.

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.