PHP AJAX PHP
In this page:
$value = $_GET["key"] ?? ""; // GET request
$value = $_POST["key"] ?? ""; // POST request
if ($value === "") {
http_response_code(400); // validate before using
}
echo json_encode($response_data);
GET-Based AJAX Requests पढ़ना
जब JavaScript एक GET method (अक्सर URL में appended query parameters के साथ) के through एक AJAX request भेजता है, PHP endpoint उस data को exactly वैसे ही पढ़ता है जैसे एक normal page के लिए करता: $_GET superglobal के through।
उदाहरण: Reading GET-Based AJAX Requests
<?php
// Set `$_GET['search']` to "php"
$_GET['search'] = "php";
// Print `json_encode(["query" => $_GET['search']])` to the output
echo json_encode(["query" => $_GET['search']]);
?>
Login to try C/C++/Java/PHP code in the editor
POST-Based AJAX Requests पढ़ना
POST method से भेजी गई AJAX requests अपना data URL के बजाय request body में carry करती हैं, और PHP उन्हें familiar $_POST superglobal के through पढ़ता है -- उन AJAX actions के लिए उपयुक्त जो server पर कुछ create, update, या delete करती हैं, POST के semantic meaning से match करते हुए।
उदाहरण: Reading POST-Based AJAX Requests
<?php
// Set `$_POST['title']` to "New Post"
$_POST['title'] = "New Post";
// Print `json_encode(["created" => $_POST['title']])` to the output
echo json_encode(["created" => $_POST['title']]);
?>
Login to try C/C++/Java/PHP code in the editor
AJAX Request Data Validate करना
एक AJAX request के through आने वाले data को exactly वही validation चाहिए जो एक regular HTML form से आने वाले data को -- यह check करना कि required fields मौजूद हैं, values expected type और format की हैं, और कुछ pass न होने पर एक clear error response return करना, चुपचाप bad data के साथ आगे बढ़ने के बजाय।
उदाहरण: Validating AJAX Request Data
<?php
// Set `$_POST['email']` to "not-an-email"
$_POST['email'] = "not-an-email";
// Check whether `!filter_var($_POST['email'], FILTER_VALIDATE_EMAIL)`
if (!filter_var($_POST['email'], FILTER_VALIDATE_EMAIL)) {
// Call `http_response_code(400)`
http_response_code(400);
// Print `json_encode(["status" => "error", "message" => "Invalid email"])` to the output
echo json_encode(["status" => "error", "message" => "Invalid email"]);
}
?>
Login to try C/C++/Java/PHP code in the editor
Structured JSON Responses Return करना
एक consistent response shape -- जैसे हमेशा एक "status" field शामिल करना ("ok" या "error"), और optionally एक "message" या "data" field -- JavaScript side के handling code को simpler और ज़्यादा predictable बनाता है, क्योंकि इसे हमेशा पता होता है कि वापस किस shape का object expect करना है।
उदाहरण: Returning Structured JSON Responses
<?php
// Print `json_encode(["status" => "ok", "data" => ["id" => 1]])` to the output
echo json_encode(["status" => "ok", "data" => ["id" => 1]]);
?>
Login to try C/C++/Java/PHP code in the editor
AJAX Endpoints में Errors को Gracefully Handle करना
एक AJAX endpoint को अपनी errors को एक well-formed response की तरह catch और report करना चाहिए (एक उपयुक्त HTTP status code के साथ), बजाय एक raw PHP error या warning को response body में leak होने देने के, जो इसे JSON की तरह parse करने की कोशिश कर रहे JavaScript को तोड़ देगा।
उदाहरण: Handling Errors Gracefully in AJAX Endpoints
<?php
// Try running this block; jump to `catch` if it throws
try {
// Throw a new `Exception` with message "Something failed"
throw new Exception("Something failed");
// Catch Exception $e
} catch (Exception $e) {
// Call `http_response_code(500)`
http_response_code(500);
// Print `json_encode(["status" => "error", "message" => "Something went wrong"])` to the output
echo json_encode(["status" => "error", "message" => "Something went wrong"]);
}
?>
Login to try C/C++/Java/PHP code in the editor
- GET-style AJAX requests ($_GET के through पढ़ी गई) और POST-style वालों ($_POST के through पढ़ी गई) के बीच distinguish न करना, और request actually कैसे की गई थी इसके लिए गलत superglobal से पढ़ना।
- सिर्फ इसलिए AJAX-submitted data पर validation skip करना कि यह किसी regular form के बजाय JavaScript से आया -- यह अभी भी untrusted user input है और इसे same scrutiny चाहिए।
- same endpoint से code path के आधार पर inconsistent response shapes return करना (कभी एक plain string, कभी JSON), JavaScript side को reliably लिखना मुश्किल बनाते हुए।
- एक PHP AJAX endpoint request data को exactly किसी दूसरी PHP script की तरह $_GET या $_POST से पढ़ता है।
- AJAX request data को validate और sanitize करना एक regular form submission जितना ही ज़रूरी है, क्योंकि यह equally untrusted है।
- एक consistent response format रखना (जैसे हमेशा एक "status" field के साथ JSON return करना) corresponding JavaScript code को simpler और ज़्यादा predictable बनाता है।
Chapter Quiz — Complete all 12 topics to unlock
0/12 topics done
Complete these topics first: