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.
उदाहरण: 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.
उदाहरण: Returning JSON from PHP for 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.
उदाहरण: Sending POST Data to PHP
// 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.
उदाहरण: Sending JSON to PHP
// 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.
उदाहरण: Validating Data on the PHP Side
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));
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