← 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.

उदाहरण: 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.

उदाहरण: Returning JSON from PHP for JavaScript

javascript
// Define the method `fetch` taking `"data.php"`
// Define the method `fetch` taking `"data.php"`
fetch("data.php")
  // On success, run this with the resolved value as `response`
  // On success, run this with the resolved value as `response`
  .then(response => response.json())
  // On success, run this with the resolved value as `data`
  // On success, run this with the resolved value as `data`
  .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.

उदाहरण: Sending POST Data to PHP

javascript
// Declare the constant `formData` as a new `FormData` instance
// Declare the constant `formData` as a new `FormData` instance
const formData = new FormData();
// Call `formData.append("name", "Sam")`
// Call `formData.append("name", "Sam")`
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 [].

उदाहरण: Sending JSON to PHP

javascript
// Send a POST request with a JSON body to save.php
fetch("save.php", {
  method: "POST",
  headers: { "Content-Type": "application/json" }, // tell the server we're sending JSON
  body: JSON.stringify({ name: "Sam" }), // convert the JS object into a JSON string
}).then(r => r.json()).then(data => console.log(data)); // parse and log the server's JSON reply

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.

उदाहरण: Validating Data on the PHP Side

javascript
fetch("register.php", {
  method: "POST",
  headers: { "Content-Type": "application/json" },
  body: JSON.stringify({ email: "" }),
})
  // On success, run this with the resolved value as `r`
  // On success, run this with the resolved value as `r`
  .then(r => r.json())
  // On success, run this with the resolved value as `data`
  // On success, run this with the resolved value as `data`
  .then(data => console.log(data.error));
Live Example
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. #}

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.