XMLHttpRequest properties (onReadyStateChange, readyState, responseText, responseXML)

चार properties हर AJAX call चलाती हैं: onreadystatechange आपकी doorbell है, readyState 0 से 4 तक journey count करती है, responseText और responseXML answer carry करते हैं, और status बताता है क्या यह good news है।

11 min read · 10 cards · 2 checks

Read in: English · हिन्दी · ગુજરાતી


Theory

किसी Asynchronous चीज़ का Wait कैसे करते हैं?

पिछले lesson का runner send() के साथ रवाना हुआ, और आपका code तुरंत आगे बढ़ गया: यही तो point था। पर फिर... आपके script को कैसे पता चलता है answer कब ARRIVE हुआ?

आप loop करके check नहीं कर सकते (इससे page freeze हो जाएगा: exactly वही disease जिसे हम cure कर रहे हैं)। जब कोई news हो तो runner को एक bell बजानी होगी।

XMLHttpRequest object उसी bell, एक progress counter, और answer के लिए 2 pockets के around बना है: 4 properties जो मिलकर हर बनाए गए AJAX call को चलाती हैं।

Theory

Bell और Counter

onreadystatechange वह function hold करता है जिसे आप चाहते हैं request की state बदलने पर call हो: इसे send करने से PEHLE assign कीजिए। यह एक बार call नहीं होता; यह journey के हर stage पर fire होता है।

readyState stage number है, 0 से 4 तक। Request आगे बढ़ते हुए scale ऊपर चलती है, और हर step आपके handler को ring करता है। जिसका आप लगभग हमेशा wait करते हैं वह है 4: finished, response ready।

Bell plus counter "मैं कैसे wait करूँ?" का asynchronous answer है: आप wait नहीं करते: आपको call किया जाता है।

At a glance

readyState 0 से 4 (Exam Table: इसे शब्दशः सीखिए)

ValueStateमतलब
0Request not initializedObject बना; open() अभी call नहीं हुआ
1Server connection establishedopen() call हो चुका है
2Request receivedsend() called; response headers पहुँचे
3Processing requestResponse body download हो रही है
4Request finished, response readyAnswer पूरी तरह हाथ में है

Theory

2 Pockets, और Verdict

जब readyState 4 पर पहुँचती है, answer 2 properties में से एक में बैठा होता है:

  • responseText: response एक plain string की तरह: JSON के लिए THE pocket (JSON.parse(xhr.responseText)) और किसी भी text के लिए
  • responseXML: response एक parsed XML document की तरह, DOM-style access के लिए ready (getElementsByTagName): सिर्फ़ तब meaningful जब server ने असल में XML भेजा हो

और एक और property verdict देती है: status, HTTP code: 200 का मतलब है OK; 404 का मतलब है not found। Finished (readyState 4) और successful (status 200) अलग facts हैं: दोनों check कीजिए।

Practical

Journey देखना, State by State (Complete Page)

<!DOCTYPE html>
<html>
<head>
  <script>
    function fetchSeats() {
      var xhr = new XMLHttpRequest();          // readyState is 0 here
      xhr.onreadystatechange = function() {    // the bell: fires per stage
        document.getElementById("log").innerHTML +=
          "readyState: " + xhr.readyState + "<br>";

        if (xhr.readyState == 4 && xhr.status == 200) {
          var data = JSON.parse(xhr.responseText);   // the string pocket
          document.getElementById("seats").innerHTML = data.seats;
        }
        if (xhr.readyState == 4 && xhr.status == 404) {
          document.getElementById("seats").innerHTML = "file missing!";
        }
      };
      xhr.open("GET", "seats.json", true);     // readyState becomes 1
      xhr.send();                              // then 2, 3, 4 as it runs
    }
  </script>
</head>
<body>
  <p>Seats: <span id="seats">?</span></p>
  <div id="log"></div>
  <button onclick="fetchSeats()">Fetch</button>
</body>
</html>

This example runs in Gri-Learn on the web, where you can edit it and see the output.

Quiz

एक AJAX handler if (xhr.readyState == 4) के अंदर, बिना किसी और condition के, page update करता है। Server 404 reply करता है क्योंकि seats.json rename हो गई थी। User क्या देखता है?

  1. कुछ नहीं: error पर readyState कभी 4 तक नहीं पहुँचती
  2. Page 404 error page के text के साथ update हो जाता है जैसे यह data हो
  3. Browser automatically request retry करता है
  4. JSON.parse तब तक wait करता है जब तक एक सही file न आए
Show the answer

Page 404 error page के text के साथ update हो जाता है जैसे यह data हो

readyState COMPLETION measure करता है, success नहीं: एक 404 response एक completed request है, तो state 4 server के error page को responseText की तरह carry करते हुए आता है, और unguarded code garbage parse या display करता है (JSON.parse का '<html>...' पर throw करना इस bug का सबसे loud symptom है)। यही वजह है canonical guard readyState == 4 AND status == 200 है: finished AND successful। Option A exact misbelief है जिसे test किया जा रहा है। Options C और D ऐसी mercies describe करते हैं जो exist नहीं करतीं: कोई retries नहीं, कोई waiting नहीं: जो response आपको मिला वही response आप handle करते हैं।

Think first

Bell कितनी बार बजती है?

Listing में Fetch click कीजिए और इसका log div पढ़िए। Tap करने से पहले: एक successful request के लिए कितनी lines दिखती हैं, कौन से numbers दिखाते हुए, और handler को if की ज़रूरत आख़िर क्यों है?

Show the answer

Typically 4 lines: 1, 2, 3, 4: onreadystatechange open() के बाद हर transition पर fire होता है (state 1 open execute होने पर, फिर 2, 3 और 4 response आते हुए; 0 creation के समय की state थी, किसी भी change के bell fire करने से पहले)। if exactly इसी multiplicity की वजह से exist करता है: आपका update-the-page code सिर्फ़ stage 4 पर चलना चाहिए: बिना guard के यह एक ऐसा answer पढ़ने की कोशिश करेगा जो अभी arrive नहीं हुआ, per request 3 बार। Bell अक्सर बजती है; आप एक बार act करते हैं।

Watch out

Property Mix-Ups जो Marks खर्च कराते हैं

responseText बनाम responseXML: text JSON.parse और display के लिए एक string है; responseXML एक pre-parsed XML DOCUMENT है: responseXML पर JSON.parse call करना, या responseText पर getElementsByTagName, दोनों category errors हैं।

Handler को send() के BAAD Assign करना: एक fast (cached) response पर, early states आपकी bell install होने से पहले fire हो सकती हैं: onreadystatechange को हमेशा send से पहले wire कीजिए।

Table को Loosely लिखना: "2 का मतलब है request received, 3 का मतलब है processing" swap नहीं होना चाहिए: exams exact wording grade करते हैं।

Theory

Pattern जो एक Unit की तरह Memorise करना है

आप जो भी raw AJAX call कभी लिखेंगे वह same 5-line skeleton है: object बनाइए, onreadystatechange assign कीजिए, 4-and-200 से guard कीजिए, open कीजिए, send कीजिए। आज की listing तब तक सीखिए जब तक आप इसे आँखें बंद करके reproduce न कर सकें: exam के AJAX questions यही skeleton हैं जिसमें URL बदला हुआ है। इसमें 2 verbs अभी unexplained हैं: open() और send() exactly क्या करते हैं, plus headers के लिए तीसरा method: अगला lesson object को finish करता है।

Summary

Key takeaways

  • onreadystatechange आपका handler hold करता है; यह हर state change पर fire होता है, तो इसके अंदर guard कीजिए।
  • readyState: 0 not initialized, 1 connection established, 2 request received, 3 processing, 4 finished and ready: table शब्दशः सीखिए।
  • responseText = answer एक string की तरह (JSON का pocket); responseXML = एक parsed XML document।
  • status HTTP verdict है: 200 OK, 404 not found।
  • Canonical guard: if (readyState == 4 && status == 200): finished AND successful।
  • Handler को send() से पहले wire कीजिए; सिर्फ़ stage 4 पर act कीजिए।
  • Memory hook: bell 4 बार बजती है; चौथी बार पर दरवाज़ा खोलिए, और check कीजिए यह कौन है।

Study this properly

This page is the lesson to read. In Gri-Learn the same topic is a graded deck: the self-checks are scored and your weak topics are tracked. Free to start.

Start this topic

Already have an account? Sign in

More from AJAX (Asynchronous JavaScript and XML)

Gri-Learn · syllabus-mapped B.C.A. lessons in English, Hindi and Gujarati

XMLHttpRequest properties (onReadyStateChange, readyState, responseText, responseXML) · Web Designing-2 (option A) · Gri-Learn