XMLHttpRequest properties (onReadyStateChange, readyState, responseText, responseXML)

ચાર properties દરેક AJAX call ને run કરે છે: onreadystatechange એ તમારો doorbell છે, readyState journey ને 0 થી 4 સુધી count કરે છે, responseText અને responseXML answer ને carry કરે છે, અને status કહે છે કે તે good news છે કે નહીં.

11 min read · 10 cards · 2 checks

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


Theory

તમે asynchronous વસ્તુ માટે કેવી રીતે wait કરો છો?

last lesson નો runner send() સાથે departed થયો, અને તમારું code immediately move on થયું: તે point હતો. પણ પછી... તમારું script ever કેવી રીતે learn કરે છે કે answer ARRIVED થયો?

તમે loop અને check નથી કરી શકતા (તે page ને freeze કરે છે: exact disease જેને આપણે cure કરી રહ્યા છીએ). runner એ bell ring કરવો પડે જ્યારે news હોય.

XMLHttpRequest object એ bell, progress counter, અને answer માટે 2 pockets ની આસપાસ built છે: 4 properties જે between them દરેક AJAX call ને run કરે છે જે ક્યારેય made થયો છે.

Theory

bell અને counter

onreadystatechange તે function ને hold કરે છે જે તમે want કરો છો called whenever request ની state changes થાય: તેને assign કરો BEFORE sending. તે once call નથી થતું; તે journey ના દરેક stage પર fires થાય છે.

readyState એ stage number છે, 0 થી 4 સુધી. request progress થાય છે તેમ scale પર up ચાલે છે, અને દરેક step તમારા handler ને rings કરે છે. એક જે તમે almost always await કરો છો તે 4: finished, response ready છે.

Bell plus counter એ asynchronous answer છે "how do I wait?" નો: તમે wait નથી કરતા: તમને called થવામાં આવે છે.

At a glance

readyState 0 થી 4 (exam table: તેને verbatim learn કરો)

ValueStateMeaning
0Request not initializedObject created; open() હજુ called નથી
1Server connection establishedopen() has been called
2Request receivedsend() called; response headers arrived
3Processing requestResponse body downloading
4Request finished, response readyAnswer fully in hand છે

Theory

બે pockets, અને verdict

જ્યારે readyState 4 પર hits થાય છે, answer 2 properties માંથી એક માં sits કરે છે:

  • responseText: response એ plain string તરીકે: JSON માટે THE pocket (JSON.parse(xhr.responseText)) અને કોઈ પણ text
  • responseXML: response એ parsed XML document તરીકે, DOM-style access માટે ready (getElementsByTagName): meaningful ફક્ત જ્યારે server actually XML send કર્યું હોય

અને એક more property verdict ને renders કરે છે: status, HTTP code: 200 એટલે OK; 404 એટલે not found. Finished (readyState 4) અને successful (status 200) એ different facts છે: બંને ને check કરો.

Practical

journey ને watching, state by state (complete page)

<!DOCTYPE html>
<html>
<head>
  <script>
    function fetchSeats() {
      var xhr = new XMLHttpRequest();          // readyState અહીં 0 છે
      xhr.onreadystatechange = function() {    // bell: દરેક stage પર fires થાય છે
        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 1 બને છે
      xhr.send();                              // પછી 2, 3, 4 જેમ તે 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 page ને update કરે છે if (xhr.readyState == 4) ની અંદર કોઈ બીજી condition વગર. server 404 reply કરે છે કારણ કે seats.json નું rename થયું. user શું જુએ છે?

  1. Nothing: readyState error પર ક્યારેય 4 સુધી પહોંચતું નથી
  2. page 404 error page ના text ને update કરે છે જેને data તરીકે poured in કરવામાં આવ્યું હોય
  3. browser request ને automatically retry કરે છે
  4. JSON.parse wait કરે છે જ્યાં સુધી correct file appear ન થાય
Show the answer

page 404 error page ના text ને update કરે છે જેને data તરીકે poured in કરવામાં આવ્યું હોય

readyState COMPLETION ને measure કરે છે, success નહીં: 404 response એ completed request છે, તેથી state 4 arrive થાય છે server ના error page ને responseText તરીકે carry કરતું, અને unguarded code garbage ને parse અથવા display કરે છે (JSON.parse '<html>...' પર throwing એ આ bug નો loudest 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 કેટલી વાર ring થાય છે?

listing માં Fetch પર click કરો અને તેના log div ને read કરો. tap કરતા પહેલાં: એક successful request માટે કેટલી lines appear થાય છે, કયા numbers ને showing, અને handler ને if ની જરૂર શા માટે છે?

Show the answer

Typically 4 lines: 1, 2, 3, 4: onreadystatechange દરેક transition પર fires થાય છે open() પછી (state 1 જેમ open execute થાય છે, પછી 2, 3 અને 4 જેમ response arrive થાય છે; 0 એ creation ની state હતી, કોઈ પણ change bell ને fire કરે તે પહેલાં). if precisely આ multiplicity ને કારણે exists કરે છે: તમારું update-the-page code ફક્ત stage 4 પર ONLY run થવું જોઈએ: guard વગર તે answer ને read કરવાનો attempt કરે છે જે હજુ arrive નથી થયું, દરેક request પર 3 વાર. Bell ઘણી વાર rings થાય છે; તમે once act કરો છો.

Watch out

Property mix-ups જે marks ને cost કરે છે

responseText vs responseXML: text એ string છે JSON.parse અને display માટે; responseXML એ pre-parsed XML DOCUMENT છે: responseXML પર JSON.parse call કરવું, અથવા responseText પર getElementsByTagName, બંને category errors છે.

handler ને send() પછી Assigning કરવું: fast (cached) response પર, early states fire થઈ શકે છે તમારા bell install થાય તે પહેલાં: હંમેશા onreadystatechange ને wire કરો send() પહેલાં.

table ને loosely Writing કરવું: "2 means request received, 3 means processing" એ swap નથી થવું જોઈએ: exams exact wording ને grade કરે છે.

Theory

pattern જેને એક unit તરીકે memorise કરવું

દરેક raw AJAX call જે તમે ever write કરશો તે same 5-line skeleton છે: object ને create કરો, onreadystatechange ને assign કરો, 4-and-200 સાથે guard કરો, open, send. today ના listing ને learn કરો જ્યાં સુધી તમે તેને તમારી eyes closed સાથે reproduce ન કરી શકો: exam AJAX questions એ this skeleton છે URL changed સાથે. બે verbs તેમાં unexplained રહે છે: open() અને send() precisely શું કરે છે, plus headers માટે ત્રીજી method: next lesson object ને finishes કરે છે.

Summary

Key takeaways

  • onreadystatechange તમારા handler ને hold કરે છે; તે દરેક state change પર fires થાય છે, તેથી તેની અંદર guard કરો.
  • readyState: 0 not initialized, 1 connection established, 2 request received, 3 processing, 4 finished and ready: table ને verbatim learn કરો.
  • 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 વાર rings થાય છે; fourth પર door ને open કરો, અને 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