← Back to PHP Course | Chapter 15: Web Development | Lesson 9 of 12

PHP AJAX PHP

एक minimal single-value response से आगे, एक real PHP AJAX endpoint को आमतौर पर incoming request data पढ़ना, इसे validate करना, कुछ actual processing करना, और एक structured response return करना ज़रूरी है -- GET और POST-based AJAX requests दोनों को reliably handle करने के लिए consistent patterns follow करते हुए।
Syntax
php
$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
<?php
// Set `$_GET['search']` to "php"
$_GET['search'] = "php";
// Print `json_encode(["query" => $_GET['search']])` to the output
echo json_encode(["query" => $_GET['search']]);
?>

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
<?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']]);
?>

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
<?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"]);
}
?>

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
<?php
// Print `json_encode(["status" => "ok", "data" => ["id" => 1]])` to the output
echo json_encode(["status" => "ok", "data" => ["id" => 1]]);
?>

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
<?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"]);
}
?>
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. #}
आम गलतियां
  1. GET-style AJAX requests ($_GET के through पढ़ी गई) और POST-style वालों ($_POST के through पढ़ी गई) के बीच distinguish न करना, और request actually कैसे की गई थी इसके लिए गलत superglobal से पढ़ना।
  2. सिर्फ इसलिए AJAX-submitted data पर validation skip करना कि यह किसी regular form के बजाय JavaScript से आया -- यह अभी भी untrusted user input है और इसे same scrutiny चाहिए।
  3. 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 बनाता है।

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.