JS का AJAX PHP
In this page:
एक Basic Fetch-to-PHP Round Trip
JavaScript का fetch() किसी .php file के URL पर ठीक वैसे ही request भेजता है जैसे किसी और endpoint पर भेजता, और PHP script उसे process करके एक response echo करती है, जिसे JavaScript फिर पढ़ता है -- client-side code में PHP-specific कुछ भी नहीं है।
उदाहरण: A Basic Fetch-to-PHP Round Trip
fetch("greet.php")
.then(response => response.text())
.then(text => console.log(text)); // PHP echoes a response back
JavaScript के लिए PHP से JSON Return करना
एक PHP endpoint header('Content-Type: application/json') सेट करके और किसी PHP array या object पर json_encode() का result echo करके ऐसा data return करता है जिसे JavaScript structural रूप से parse कर सकता है -- फिर JavaScript side बस एक usable JavaScript value वापस पाने के लिए response.json() कॉल करता है।
उदाहरण: 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));
PHP को POST Data भेजना
JavaScript से एक POST request अपना data form-encoded (वह traditional format जिसे PHP का $_POST अपने आप पढ़ता है) के रूप में या एक JSON body (जिसे PHP को php://input के ज़रिए manually पढ़ना पड़ता है) के रूप में भेज सकता है -- दोनों काम करते हैं, पर form-encoding को सबसे कम अतिरिक्त 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));
PHP को JSON भेजना
जब request body form-encoded के बजाय JSON हो, तो PHP को इसे manually पढ़ना होगा: file_get_contents('php://input') raw request body लाता है, और json_decode() इसे एक PHP array या object में बदल देता है, क्योंकि एक JSON-formatted body के लिए $_POST खाली ही रहता है।
उदाहरण: 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
PHP Side पर Data Validate करना
एक regular form submission की तरह ही, किसी AJAX request से आने वाले किसी भी data को भरोसा किए जाने या store होने से पहले server-side validation चाहिए -- required fields, सही formats, और appropriate types जांचना, और validation fail होने पर एक साफ JSON error response return करना।
उदाहरण: 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));
- यह मान लेना कि कोई PHP endpoint Content-Type: application/json header explicitly set किए बिना और response data पर json_encode() कॉल किए बिना automatically JSON return करता है।
- यह भूल जाना कि एक PHP script GET data को $_GET के ज़रिए और POST data को $_POST के ज़रिए पढ़ती है -- गलत method से data भेजने पर PHP script गलत जगह देखती रह जाती है।
- PHP side पर JavaScript से भेजा गया data validate या sanitize न करना, क्योंकि client-side data AJAX से आते हुए भी बिल्कुल उतना ही untrustworthy है जितना किसी regular HTML form से।
- एक PHP AJAX endpoint incoming data को $_GET या $_POST से पढ़ता है, बिल्कुल वैसे ही जैसे वह किसी regular page request के लिए करता।
- PHP side पर json_encode() किसी PHP array या object को एक JSON string में convert करता है जिसे JavaScript fetch call response.json() से parse कर सकता है।
- JavaScript से PHP को भेजा गया data किसी regular form से आए data जितना ही untrusted है, और उसे same validation और sanitization चाहिए।
AJAX requests किसी PHP backend के साथ किसी भी दूसरी server-side language की तरह ही समान रूप से काम करते हैं, क्योंकि browser side पूरी तरह 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