← Back to JavaScript Course | Chapter 9: Async & Web APIs | Lesson 11 of 26

JS AJAX परिचय

AJAX को समझना उस request/response cycle से शुरू होता है जिसे यह automate करता है: JavaScript एक request शुरू करता है, browser उसे background में server को भेजता है, और response आने पर, एक callback (या resolved promise) उसे process करता है -- यह सब बिना user को किसी full-page reload या रुकावट का एहसास कराए।

Request/Response Cycle

एक AJAX interaction के तीन stages होते हैं: आपका JavaScript code एक request शुरू करता है (एक URL और optional data बताते हुए), browser उसे server को भेजता है और background में इंतज़ार करता है, और response आने पर, आपका registered callback या promise handler उसे process करता है।

Note: AJAX code लिखने से पहले तीन stages -- initiate, wait, handle -- को स्केच करें, ताकि asynchronous flow आपके मन में साफ रहे।
Warning: किसी AJAX call के ठीक बाद लिखा गया code, यह उम्मीद करते हुए कि response पहले से उपलब्ध होगा, response के असल में आने से पहले ही चल जाएगा -- यह beginners के लिए सबसे आम AJAX गलती है।

उदाहरण: The Request/Response Cycle

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("Response handled:", data));

AJAX Requests Asynchronous क्यों होते हैं

किसी server को network request server और connection के हिसाब से milliseconds से लेकर कई seconds तक ले सकती है -- अगर JavaScript आगे बढ़ने से पहले हर request के खत्म होने का इंतज़ार करता (block होता), तो उस इंतज़ार के दौरान पूरा page freeze होकर unresponsive हो जाता, जिससे asynchronous requests ठीक-ठीक बचाती हैं।

Note: AJAX की asynchronous प्रकृति से लड़ने के बजाय उसे अपनाएं -- synchronous-style इंतज़ार जबरदस्ती करने की कोशिश करने के बजाय अपने code को callbacks, promises, या async/await के इर्द-गिर्द structure करें।
Warning: XMLHttpRequest का एक synchronous version technically मौजूद है पर deprecated है और request के दौरान पूरे page को freeze कर देता है -- इसे modern code में कभी इस्तेमाल नहीं करना चाहिए।

उदाहरण: Why AJAX Requests Are Asynchronous

javascript
console.log("Request started");
fetch("data.php").then(r => r.json()).then(data => console.log("Response arrived:", data));
console.log("Page stays responsive while waiting"); // logs before the fetch resolves

Same-Origin Policy और CORS

डिफ़ॉल्ट रूप से, एक browser JavaScript को page से अलग origin (domain, protocol, या port) पर AJAX request बनाने से रोकता है, एक security measure के तौर पर -- एक server CORS (Cross-Origin Resource Sharing) response headers भेजकर explicitly cross-origin requests को allow करने के लिए opt in कर सकता है।

Note: जब किसी अलग domain को AJAX request CORS-related console error के साथ fail हो, तो उस server को appropriate Access-Control-Allow-Origin header जोड़ने की ज़रूरत है -- यह सिर्फ client side से ठीक नहीं किया जा सकता।
Warning: एक CORS error browser console में दिखती है पर JavaScript में एक normal network error की तरह catch नहीं की जा सकती, क्योंकि browser response को आपके code के देखने से पहले ही block कर देता है।

उदाहरण: Same-Origin Policy and CORS

javascript
fetch("data.php").then(r => r.json()).then(data => console.log(data));
// Cross-origin requests need the server to send CORS headers to be allowed

Success और Failure संभालना

एक अच्छी तरह बनाई गई AJAX interaction दोनों outcomes के लिए plan करती है: एक successful response जो page update करे, और एक failed request (network error, timeout, या server error) जो user को उसे एक अटकी हुई loading state पर घूरते छोड़ने के बजाय एक साफ message दिखाए।

Note: हमेशा एक .then() success handler को एक .catch() (या await के आसपास एक try/catch) failure handler के साथ जोड़ें, ताकि किसी failed request के पास जाने के लिए कोई तय जगह हो।
Warning: एक AJAX request जो बिना किसी दिखने वाले feedback और console error handling के चुपचाप fail हो जाती है, users को इस बात को लेकर उलझन में छोड़ देती है कि कुछ हुआ भी या नहीं।

उदाहरण: Handling Success and Failure

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 => {
    if (!response.ok) throw new Error("Request failed");
    // Return `response.json()` from this function
    // Return `response.json()` from this function
    return 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("Success:", data))
  // On failure, run this with the error as `error`
  // On failure, run this with the error as `error`
  .catch(error => console.log("Show user a message:", error.message));

एक पूरा Beginner AJAX Example

इस introduction की हर चीज़ को मिलाकर: एक button click एक request शुरू करता है, page इंतज़ार के दौरान एक loading state दिखाता है, और response (success या failure) page को update करता है -- यह वह पूरी, न्यूनतम shape है जो हर AJAX interaction follow करती है, चाहे असली application logic कितनी भी जटिल क्यों न हो।

Note: आप जो भी नई AJAX interaction बनाएं उसके लिए इसी basic shape -- trigger, loading state, success/failure handling -- को mental template के रूप में इस्तेमाल करें।
Warning: किसी ऐसी request पर loading-state feedback छोड़ देना जिसमें एक ध्यान देने लायक पल लग सकता है, किसी application को unresponsive या टूटा हुआ महसूस करा सकता है, भले ही वह असल में सही से काम कर रहा हो।

उदाहरण: A Complete Beginner AJAX Example

javascript
<button id="loadBtn">Load Data</button>
<p id="status">Idle</p>
<script>
  document.getElementById("loadBtn").addEventListener("click", () => {
    document.getElementById("status").textContent = "Loading...";
    // Define the method `fetch` taking `"data.php"`
    fetch("data.php")
      // On success, run this with the resolved value as `r`
      .then(r => r.json())
      // On success, run this with the resolved value as `data`
      .then(data => document.getElementById("status").textContent = "Loaded: " + data.message)
      .catch(() => document.getElementById("status").textContent = "Failed");
  });
</script>
Live Example
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 request instantly और synchronously पूरा हो जाएगा, जबकि यह fundamentally asynchronous है -- request call के बाद का code response आने से पहले तुरंत चलता है।
  2. request के fail होने (network issue, server error) की planning न करना और उस स्थिति के लिए कोई fallback behavior न छोड़ना।
  3. यह भूल जाना कि AJAX request अभी भी एक असली HTTP request है, जो browser से किसी भी cross-domain request को govern करने वाली same-origin policy और CORS rules के अधीन है।
चैप्टर सारांश
  • एक AJAX request एक predictable flow follow करता है: request शुरू करें, asynchronously wait करें, response आने पर उसे handle करें।
  • AJAX requests response का इंतज़ार करते हुए page के बाकी JavaScript को चलने से कभी नहीं रोकते।
  • Cross-origin AJAX requests (page से अलग domain पर) browser द्वारा enforce किए गए CORS restrictions के अधीन होते हैं।
ब्राउज़र सपोर्ट

AJAX के पीछे का asynchronous request/response pattern XMLHttpRequest और fetch दोनों के ज़रिए हर browser में supported है।

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.