JS AJAX PHP
In this page:
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
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
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
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
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
fetch("register.php", {
method: "POST",
headers: { "Content-Type": "application/json" },
body: JSON.stringify({ email: "" }),
})
.then(r => r.json())
.then(data => console.log(data.error));
- Assuming a PHP endpoint automatically returns JSON without explicitly setting the Content-Type: application/json header and calling json_encode() on the response data.
- 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.
- 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.
- 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.
AJAX requests work identically with a PHP backend as with any other server-side language, since the browser side is entirely language-agnostic.
Chapter Quiz — Complete all 26 topics to unlock
0/26 topics done
Complete these topics first:
- JS JSON
- JS Regular Expressions
- JS Fetch API
- JS LocalStorage and SessionStorage
- JS Cookies
- JS setTimeout and setInterval
- JS Event Loop
- JS Web Workers
- JS Service Workers
- JS AJAX
- JS AJAX Intro
- JS AJAX XMLHttp
- JS AJAX Request
- JS AJAX Response
- JS AJAX XML
- JS AJAX PHP
- JS AJAX Database
- JS JSONP
- JS RegExp Flags
- JS RegExp Classes
- JS RegExp Metachars
- JS RegExp Assertions
- JS RegExp Groups
- JS RegExp Quantifiers
- JS JSON HTML
- JS JSON vs XML