JS AJAX परिचय
In this page:
Request/Response Cycle
एक AJAX interaction के तीन stages होते हैं: आपका JavaScript code एक request शुरू करता है (एक URL और optional data बताते हुए), browser उसे server को भेजता है और background में इंतज़ार करता है, और response आने पर, आपका registered callback या promise handler उसे process करता है।
उदाहरण: The Request/Response Cycle
// 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 ठीक-ठीक बचाती हैं।
उदाहरण: Why AJAX Requests Are Asynchronous
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 कर सकता है।
उदाहरण: Same-Origin Policy and CORS
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 दिखाए।
उदाहरण: Handling Success and Failure
// 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 कितनी भी जटिल क्यों न हो।
उदाहरण: A Complete Beginner AJAX Example
<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>
- यह उम्मीद करना कि कोई AJAX request instantly और synchronously पूरा हो जाएगा, जबकि यह fundamentally asynchronous है -- request call के बाद का code response आने से पहले तुरंत चलता है।
- request के fail होने (network issue, server error) की planning न करना और उस स्थिति के लिए कोई fallback behavior न छोड़ना।
- यह भूल जाना कि 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 है।
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