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

JS का AJAX XMLHttp

XMLHttpRequest object AJAX requests बनाने के लिए मूल browser API है, और भले ही नए code के लिए fetch() prefer किया जाता है, XMLHttpRequest के readyState-based lifecycle को समझना पुराने code को maintain करने और यह समझने के लिए उपयोगी बना रहता है कि browsers अंदर से HTTP requests कैसे लागू करते हैं।
Syntax
javascript
const xhr = new XMLHttpRequest();
xhr.onreadystatechange = function() {
  if (this.readyState == 4 && this.status == 200) {
    // this.responseText
  }
};
xhr.open("GET", url);
xhr.send();

एक Request बनाना और Configure करना

new XMLHttpRequest() एक नया request object बनाता है, और .open(method, url, async) इसे एक HTTP method, target URL, और यह चाहिए कि यह asynchronously चले या नहीं (modern code में लगभग हमेशा true) के साथ configure करता है -- यह सिर्फ configuration है, इस point पर अभी कुछ भेजा नहीं गया है।

Note: asynchronous requests के लिए हमेशा true पास करें (या तीसरा argument छोड़ दें, क्योंकि यह default true होता है) -- synchronous mode deprecated है और page को block करता है।
Warning: एक ही XMLHttpRequest object पर एक से ज़्यादा बार .open() कॉल करना इसे पूरी तरह reconfigure कर देता है, असल में पिछले किसी भी configuration को छोड़ते हुए।

उदाहरण: Creating and Configuring a Request

javascript
const xhr = new XMLHttpRequest();
xhr.open("GET", "data.php", true); // configured, nothing sent yet
console.log(xhr.readyState); // 1 - opened

readyState Lifecycle

किसी request के आगे बढ़ने पर readyState पांच numeric values से गुज़रता है: 0 (uninitialized), 1 (opened), 2 (headers received), 3 (loading), और 4 (done) -- onreadystatechange event हर बार यह value बदलने पर fire होता है, जो आपको किसी भी stage पर react करने देता है, हालांकि खासतौर पर 4 जांचना सबसे आम pattern है।

Note: यह पता लगाने के लिए कि request पूरी तरह पूरी हो चुकी है readyState === 4 जांचें, क्योंकि typical code में intermediate states को शायद ही अलग handling की ज़रूरत होती है।
Warning: onreadystatechange किसी request के lifecycle में कई बार fire होता है -- उसके अंदर के code को खास readyState value जांचनी ही चाहिए, वरना यह किसी पहले वाले stage पर समय से पहले चल जाएगा।

उदाहरण: The readyState Lifecycle

javascript
// Declare the constant `xhr` as a new `XMLHttpRequest` instance
// Declare the constant `xhr` as a new `XMLHttpRequest` instance
const xhr = new XMLHttpRequest();
// Assign `() => console.log("readyState:", xhr.readyState)` to `xhr.onreadystatechange`
// Assign `() => console.log("readyState:", xhr.readyState)` to `xhr.onreadystatechange`
xhr.onreadystatechange = () => console.log("readyState:", xhr.readyState);
// Call `xhr.open("GET", "data.php")`
// Call `xhr.open("GET", "data.php")`
xhr.open("GET", "data.php");
// Call `xhr.send()`
// Call `xhr.send()`
xhr.send();

HTTP Status Code जांचना

readyState के 4 तक पहुंचने पर, status property server द्वारा return किया गया असली HTTP status code रखती है -- success के लिए 200, not found के लिए 404, server error के लिए 500 -- और readyState के साथ इसे जांचना सच में सफल response को एक completed-but-failed response से अलग करने के लिए ज़रूरी है।

Note: readyState === 4 के साथ हमेशा xhr.status जांचें (आमतौर पर 200-299 range के लिए), क्योंकि एक completed request अभी भी एक HTTP-level failure को represent कर सकती है।
Warning: सिर्फ readyState === 4 को success मान लेना एक आम bug है -- एक 404 या 500 response भी readyState 4 तक पहुंचती है, बस एक ऐसे status code के साथ जो failure दिखाता है।

उदाहरण: Checking the HTTP Status Code

javascript
// Declare the constant `xhr` as a new `XMLHttpRequest` instance
// Declare the constant `xhr` as a new `XMLHttpRequest` instance
const xhr = new XMLHttpRequest();
// Assign `() => {` to `xhr.onreadystatechange`
// Assign `() => {` to `xhr.onreadystatechange`
xhr.onreadystatechange = () => {
  // Check whether `xhr.readyState === 4`
  // Check whether `xhr.readyState === 4`
  if (xhr.readyState === 4) {
    // Print `xhr.status === 200 ? "Success" : "Failed with status " + xhr.status` to the console
    // Print `xhr.status === 200 ? "Success" : "Failed with status " + xhr.status` to the console
    console.log(xhr.status === 200 ? "Success" : "Failed with status " + xhr.status);
  }
};
// Call `xhr.open("GET", "data.php")`
// Call `xhr.open("GET", "data.php")`
xhr.open("GET", "data.php");
// Call `xhr.send()`
// Call `xhr.send()`
xhr.send();

Request भेजना और Errors संभालना

.send() असल में configured request को भेजता है -- POST/PUT requests के लिए एक optional body argument के साथ -- और अलग onload/onerror event handlers (XMLHttpRequest में थोड़ा ज़्यादा modern addition) basic success/failure handling के लिए manually readyState जांचने का एक साफ विकल्प देते हैं।

Note: जब आपको सिर्फ आखिरी success या failure outcome पर react करना हो, तो सरल code के लिए .onreadystatechange के बजाय .onload और .onerror इस्तेमाल करने पर विचार करें।
Warning: .onerror सिर्फ network-level failures के लिए fire होता है (जैसे request का server तक कभी न पहुंचना) -- 500 जैसा एक HTTP error status अभी भी .onload को trigger करता है, .onerror को नहीं, क्योंकि request technically पूरी हुई थी।

उदाहरण: Sending the Request and Handling Errors

javascript
// Declare the constant `xhr` as a new `XMLHttpRequest` instance
// Declare the constant `xhr` as a new `XMLHttpRequest` instance
const xhr = new XMLHttpRequest();
// Assign `() => console.log("Loaded:", xhr.responseText)` to `xhr.onload`
// Assign `() => console.log("Loaded:", xhr.responseText)` to `xhr.onload`
xhr.onload = () => console.log("Loaded:", xhr.responseText);
// Assign `() => console.log("Request failed")` to `xhr.onerror`
// Assign `() => console.log("Request failed")` to `xhr.onerror`
xhr.onerror = () => console.log("Request failed");
// Call `xhr.open("GET", "data.php")`
// Call `xhr.open("GET", "data.php")`
xhr.open("GET", "data.php");
// Call `xhr.send()`
// Call `xhr.send()`
xhr.send();

XMLHttpRequest बनाम fetch: एक सीधी तुलना

एक जैसी GET request को साथ-साथ रखना fetch के फायदे को साफ तौर पर उजागर करता है: कम lines, कोई manual readyState checking नहीं, और native promise chaining -- यही वजह है कि fetch नए code के लिए default recommendation बन गया है, जबकि XMLHttpRequest की जानकारी मुख्यतः legacy code के लिए उपयोगी बनी हुई है।

Note: किसी मौजूदा codebase में XMLHttpRequest मिलने पर, इसे maintain करने लायक अच्छे से समझें, पर कोई भी बिल्कुल नया AJAX code इसके बजाय fetch से लिखें।
Warning: बिना किसी असली functional ज़रूरत के, सिर्फ style के लिए काम कर रहे बड़ी मात्रा में XMLHttpRequest code को fetch में फिर से लिखना बिना किसी ठोस फायदे के regressions ला सकता है -- किसी migration की असली value को तौलें।

उदाहरण: XMLHttpRequest vs fetch: A Direct Comparison

javascript
// Declare the constant `xhr` as a new `XMLHttpRequest` instance
// Declare the constant `xhr` as a new `XMLHttpRequest` instance
const xhr = new XMLHttpRequest();
// Assign `() => console.log(xhr.responseText)` to `xhr.onload`
// Assign `() => console.log(xhr.responseText)` to `xhr.onload`
xhr.onload = () => console.log(xhr.responseText);
// Call `xhr.open("GET", "data.php")`
// Call `xhr.open("GET", "data.php")`
xhr.open("GET", "data.php");
// Call `xhr.send()`
// Call `xhr.send()`
xhr.send();

// Call `fetch("data.php").then(r => r.text()).then(text => console.log(text))`
// Call `fetch("data.php").then(r => r.text()).then(text => console.log(text))`
fetch("data.php").then(r => r.text()).then(text => console.log(text));
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. status check किए बिना सिर्फ readyState check करना, जो किसी failed request (जैसे 404) पर completion handler को ऐसे trigger कर सकता है जैसे वह succeed हुआ हो।
  2. गलत argument order के साथ .open() कॉल करना या बाद में .send() कॉल करना भूल जाना, request को configured तो रखते हुए लेकिन कभी actually भेजे बिना।
  3. .open() कॉल करने से पहले .setRequestHeader() से request headers set करना, जबकि इसे open() के बाद लेकिन send() से पहले कॉल किया जाना चाहिए।
चैप्टर सारांश
  • new XMLHttpRequest() एक request object बनाता है, .open(method, url) उसे configure करता है, और .send() असल में उसे fire करता है।
  • readyState request के lifecycle stage को 0 (uninitialized) से 4 (complete) तक track करता है, आमतौर पर onreadystatechange के अंदर check किया जाता है।
  • status response आने पर HTTP status code (जैसे 200 या 404) रखता है, और इसे readyState के साथ check किया जाना चाहिए।
ब्राउज़र सपोर्ट

XMLHttpRequest को 2000s की शुरुआत से हर browser में support मिला है और backward compatibility के लिए आज भी 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.