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

PHP AJAX Intro

एक normal web page हर बार server से नया data चाहिए होने पर पूरी तरह reload होता है -- notification count update करने जैसी छोटी चीज़ के लिए एक jarring, धीमा experience। AJAX (Asynchronous JavaScript and XML) एक page को background में server को एक request भेजने और data वापस पाने देता है, बिना पूरा reload किए page के सिर्फ हिस्से को update करते हुए।
Syntax
php
header("Content-Type: application/json");
echo json_encode(["key" => value]);

AJAX Actually क्या है

AJAX एक single technology नहीं है, बल्कि एक technique है: browser में JavaScript background में एक server को एक HTTP request भेजता है (current page से दूर navigate किए बिना), और response वापस आते ही, JavaScript page के content के सिर्फ relevant हिस्से को update करता है।

उदाहरण: What AJAX Actually Is

php
<?php
// Call `header("Content-Type: application/json")`
header("Content-Type: application/json");
// Print `json_encode(["message" => "This is what a background request returns"])` to the output
echo json_encode(["message" => "This is what a background request returns"]);
?>

एक AJAX Endpoint की तरह PHP का Role

PHP के perspective से, एक AJAX request handle करना एक normal page request handle करने जैसा लगभग identical दिखता है -- यह एक HTTP request receive करता है (अक्सर $_GET या $_POST data के साथ), इसे process करता है, और एक response वापस भेजता है।

इकलौता real अंतर यह है कि response आमतौर पर एक पूरे HTML page की तरह render होने के बजाय JavaScript द्वारा consume किया जाता है।

उदाहरण: PHP's Role as an AJAX Endpoint

php
<?php
// Set `$_GET['id']` to "5"
$_GET['id'] = "5";
// Print `json_encode(["id" => $_GET['id'], "processed" => true])` to the output
echo json_encode(["id" => $_GET['id'], "processed" => true]);
?>

JSON: AJAX के लिए Modern Data Format

AJAX के नाम में XML reference करने के बावजूद, modern AJAX requests overwhelmingly इसके बजाय JSON exchange करती हैं -- यह ज़्यादा compact है, JavaScript objects और arrays पर naturally map होता है, और PHP के पास इसे produce और consume करना trivial बनाने वाले built-in json_encode() और json_decode() functions हैं।

उदाहरण: JSON: The Modern Data Format for AJAX

php
<?php
// Declare `$data` as an array: `["name" => "Alice", "age" => 30]`
$data = ["name" => "Alice", "age" => 30];
// Print `json_encode($data)` to the output
echo json_encode($data);
// Declare `$decoded`, set to `json_decode(json_encode($data), true)`
$decoded = json_decode(json_encode($data), true);
// Print a human-readable dump of `$decoded`
print_r($decoded);
?>

एक Basic AJAX Request/Response Cycle

इसे end to end साथ रखते हुए: JavaScript का fetch() एक PHP endpoint को एक request भेजता है, वह PHP script request process करती है और एक response output करती है (आमतौर पर JSON), और JavaScript का .then() callback उस response को receive करके page update करने के लिए इस्तेमाल करता है।

उदाहरण: A Basic AJAX Request/Response Cycle

php
<?php
// Call `header("Content-Type: application/json")`
header("Content-Type: application/json");
// Print `json_encode(["status" => "ok", "message" => "Received by fetch(), consumed in .then()"])` to the output
echo json_encode(["status" => "ok", "message" => "Received by fetch(), consumed in .then()"]);
?>

User Experience के लिए AJAX क्यों मायने रखता है

AJAX उन responsive, app-like interactions को enable करता है जिनकी users अब web से उम्मीद रखते हैं -- type करते समय live search suggestions, एक "like" button जो instantly update होता है, form validation जो बिना reload के errors दिखाता है -- ये सब चीज़ें जिन्हें एक traditional full-page-reload model तुलनात्मक रूप से clumsily handle करता है।

उदाहरण: Why AJAX Matters for User Experience

php
<?php
// Check whether `!function_exists('str_starts_with')`
if (!function_exists('str_starts_with')) {
    // Define the function `str_starts_with` taking `$haystack`, `$needle`
    function str_starts_with($haystack, $needle) { return substr($haystack, 0, strlen($needle)) === $needle; }
}
// Set `$_GET['query']` to "ph"
$_GET['query'] = "ph";
// Declare `$suggestions` as an array: `["php", "phpunit", "phpmailer"]`
$suggestions = ["php", "phpunit", "phpmailer"];
// Declare `$matches`, set to `array_filter($suggestions, function ($s) { return str_starts_with($s, $_GET['query']); })`
$matches = array_filter($suggestions, function ($s) { return str_starts_with($s, $_GET['query']); });
// Print `json_encode(array_values($matches))` to the output
echo json_encode(array_values($matches));
?>
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. AJAX को एक specific technology से confuse करना -- यह JavaScript के fetch/XMLHttpRequest को एक server endpoint के साथ combine करने वाली एक technique है, खुद कोई library या language feature नहीं।
  2. यह भूल जाना कि AJAX में "XML" काफी हद तक historical है -- modern AJAX requests लगभग हमेशा JSON exchange करती हैं, actual XML documents नहीं।
  3. यह मान लेना कि एक AJAX request automatically उसी PHP session तक access रखती है जिस page ने इसे trigger किया, बिना यह confirm किए कि cookies/session handling सही से configured है।
चैप्टर सारांश
  • AJAX browser में JavaScript को पूरा page reload किए बिना एक server endpoint को एक request भेजने और एक response receive करने देता है।
  • AJAX में PHP का role बस एक normal server endpoint होना है -- यह request receive करता है, इसे process करता है, और एक response वापस भेजता है, बिल्कुल एक regular page load के लिए जैसे करता।
  • नाम की historical origin के बावजूद, modern AJAX overwhelmingly JSON data exchange करता है actual XML नहीं।

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.