AJAX and Fetch API: Asynchronous HTTP Requests Notes in Hindi & English : AJAX और Fetch API: एसिंक्रोनस HTTP रिक्वेस्ट और रिस्पॉन्स हैंडलिंग और 20 महत्वपूर्ण MCQ प्रश्न (Rajasthan IT Exam)

Post a Comment

PGDCA, BCA, B-Tech, MCA, M-Tech, B.Sc computer science राजस्थान सूचना सहायक व कंप्यूटर शिक्षक विशेष नोट्स: इस अध्याय में हम AJAX and Fetch API: Asynchronous HTTP Requests (AJAX और Fetch API: एसिंक्रोनस HTTP रिक्वेस्ट और रिस्पॉन्स हैंडलिंग) की संपूर्ण थ्योरी, मुख्य तकनीकी बिंदु, तुलनात्मक तालिका और विगत परीक्षाओं के पैटर्न पर आधारित 20 अति-महत्वपूर्ण बहुविकल्पीय प्रश्न (MCQs) विस्तृत हिंदी व अंग्रेजी व्याख्या सहित पढ़ेंगे।

Overview: AJAX and the modern Fetch API perform asynchronous background HTTP requests without full page reloads, using XMLHttpRequest callbacks or Promise/async-await response streams.

अध्याय सार: AJAX और आधुनिक Fetch API पूरे वेब पेज को रीलोड किए बिना बैकग्राउंड में सर्वर से HTTP डेटा लाने-भेजने (Asynchronous Requests) की तकनीक हैं; Fetch Promise और async/await पर आधारित है।

AJAX and Fetch API: Asynchronous HTTP Requests: Detailed Notes & Architecture (AJAX और Fetch API: एसिंक्रोनस HTTP रिक्वेस्ट और रिस्पॉन्स हैंडलिंग)

1. AJAX Concept & Legacy XMLHttpRequest (XHR) (AJAX अवधारणा व XMLHttpRequest (XHR))

[EN] AJAX (Asynchronous JavaScript and XML) lets web pages communicate with servers seamlessly in the background and dynamically refresh DOM parts. Historically powered by XMLHttpRequest (tracking readyState 0 to 4 and status 200), modern apps still rely on AJAX principles via JSON payloads rather than literal XML.

[HI] AJAX (Asynchronous JavaScript and XML) से बिना पूरा पेज रिफ्रेश किए सर्वर से बैकग्राउंड में डेटा लाकर DOM का केवल आवश्यक हिस्सा अपडेट किया जाता है। पहले इसके लिए XMLHttpRequest (readyState 0 से 4) उपयोग होता था।

2. Modern Promise-Based Fetch API & async/await (आधुनिक Promise आधारित Fetch API)

[EN] fetch(url, options) replaces verbose XHR callbacks with clean Promises. Reading a server payload happens in two asynchronous steps: first await fetch(url) resolves to a Response object as soon as HTTP headers arrive, and second await res.json() (or res.text()) downloads and parses the full body stream.

[HI] fetch(url, options) सीधा Promise लौटाता है जिसे async/await से पढ़ना बहुत सरल है। पहले await fetch() से Response हेडर मिलते हैं, फिर res.json() से पूरा बॉडी डेटा पार्स होता है।

3. CRITICAL Fetch Trap: HTTP 404/500 Errors & response.ok (Fetch का महत्वपूर्ण नियम: HTTP 404/500 त्रुटि हैंडलिंग)

[EN] A top exam and interview trap: fetch() ONLY rejects its Promise on actual network failures (DNS failure, offline, CORS block). HTTP error status codes like 404 Not Found or 500 Server Error STILL RESOLVE the fetch Promise cleanly! Developers MUST explicitly check if (!response.ok) before parsing JSON.

[HI] महत्वपूर्ण तथ्य: fetch() नेटवर्क टूटने पर ही reject होता है; सर्वर से 404 या 500 एरर आने पर भी यह resolve होता है! इसलिए डेटा पार्स करने से पहले response.ok (status 200-299) जांचना अनिवार्य है।

4. Sending POST Requests, CORS & Request Cancellation (POST रिक्वेस्ट, CORS व AbortController)

[EN] To send JSON via POST, pass method: 'POST', headers: { 'Content-Type': 'application/json' }, and body: JSON.stringify(payload). Cross-origin requests obey CORS policies (Access-Control-Allow-Origin), and timeouts or cancelled requests are handled cleanly with AbortController().

[HI] POST रिक्वेस्ट में method: 'POST', Content-Type हेडर और JSON.stringify(data) वाला body भेजा जाता है। दूसरे डोमेन के लिए सर्वर पर CORS अनुमति और रिक्वेस्ट बीच में रोकने हेतु AbortController उपयोग होता है।

Syntax, Formula & Technical Example (AJAX and Fetch API: Asynchronous HTTP Requests)

async function loadTopic(id) {
  const controller = new AbortController();
  const res = await fetch('/api/topic/' + id, { signal: controller.signal });
  if (!res.ok) throw new Error('HTTP Error: ' + res.status);
  return await res.json();
}

AJAX and Fetch API: Asynchronous HTTP Requests Quick Reference & Comparison Table

Feature / PropertyXMLHttpRequest (XHR)Modern Fetch API
Async PatternEvent callbacks (onreadystatechange)Promise-based (clean with async/await)
404 / 500 StatusResolved cleanly via xhr.status checkResolves! Must inspect response.ok manually
CancellationCalls xhr.abort() directlyUses AbortController + signal option
Default CookiesSame-origin sent automaticallySame-origin default (credentials: 'same-origin')

AJAX and Fetch API: Asynchronous HTTP Requests Top 20 Bilingual MCQs with Answers

Q1. What does the acronym AJAX stand for in web development?

(वेब डेवलपमेंट में AJAX का पूर्ण रूप (Full Form) क्या है?)

(A) Automated JSON and XHTML

(B) Asynchronous JavaScript and XML

(C) Asynchronous Java and XMLHttp

(D) Active Java Application Extension

Correct Answer: (B)

[EN] Coined by Jesse James Garrett in 2005, AJAX stands for Asynchronous JavaScript and XML (though JSON is now preferred).

[HI] AJAX का पूरा नाम Asynchronous JavaScript and XML है, हालांकि आज XML की जगह JSON प्रमुखता से चलता है।

Q2. When the server returns HTTP 404 Not Found to fetch('/missing'), does the fetch() Promise reject automatically?

(यदि सर्वर से HTTP 404 Not Found आए, तो क्या fetch('/missing') का Promise स्वतः reject होता है?)

(A) Yes, 4xx and 5xx always trigger .catch()

(B) Only 500 errors resolve

(C) Browser throws uncaught ReferenceError

(D) No, fetch() STILL resolves normally; you must check response.ok or response.status

Correct Answer: (D)

[EN] fetch() only rejects on network failures or aborted requests—never on valid HTTP error responses like 404 or 500.

[HI] fetch() केवल नेटवर्क फेल होने पर reject होता है; 404 या 500 पर भी resolve होता है, अतः response.ok जांचना जरूरी है।

Q3. Which boolean property on a Fetch Response object is true exclusively for HTTP status codes 200 through 299?

(Fetch के Response ऑब्जेक्ट की कौन सी प्रॉपर्टी केवल 200–299 सफल HTTP स्टेटस पर true होती है?)

(A) response.ok

(B) response.valid

(C) response.success

(D) response.done

Correct Answer: (A)

[EN] response.ok simplifies validating 2xx success codes without manually testing status >= 200 && status < 300.

[HI] response.ok (true/false) बताता है कि सर्वर ने 200–299 के बीच सफल स्टेटस कोड लौटाया है।

Q4. In legacy XMLHttpRequest, what readyState integer value indicates the request is finished and response is ready?

(पुराने XMLHttpRequest में readyState का कौन सा मान दर्शाता है कि रिक्वेस्ट पूरी होकर रिस्पॉन्स तैयार है?)

(A) 4 (DONE)

(B) 0 (UNSENT)

(C) 3 (LOADING)

(D) 2 (HEADERS_RECEIVED)

Correct Answer: (A)

[EN] XHR readyStates range from 0 (UNSENT) to 4 (DONE); check readyState === 4 && status === 200.

[HI] XHR में readyState 4 (DONE) का अर्थ है कि पूरा डेटा डाउनलोड होकर तैयार है।

Q5. Which API cancels an in-flight Fetch API HTTP request cleanly?

(चल रही Fetch API रिक्वेस्ट को बीच में रद्द (Cancel) करने के लिए कौन सा वेब API उपयोग होता है?)

(A) Promise.abort()

(B) fetch.cancel()

(C) AbortController (passing controller.signal)

(D) XMLHttpRequest.stop()

Correct Answer: (C)

[EN] Passing signal: controller.signal lets controller.abort() abort an active request cleanly, triggering an AbortError.

[HI] AbortController बनाकर उसका signal fetch में पास करने और controller.abort() चलाने से रिक्वेस्ट रद्द हो जाती है।

Q6. When sending JSON data via Fetch POST, which HTTP header MUST be paired with body: JSON.stringify(data)?

(Fetch से POST द्वारा JSON डेटा भेजते समय body के साथ कौन सा HTTP हेडर भेजना आवश्यक होता है?)

(A) 'Content-Type': 'application/json'

(B) 'Content-Transfer': 'text'

(C) 'Accept-Encoding': 'json'

(D) 'MIME-Type': 'javascript'

Correct Answer: (A)

[EN] Servers inspect the Content-Type header to parse the request body correctly as JSON.

[HI] सर्वर को यह बताने के लिए कि भेजा गया डेटा JSON है, Content-Type: application/json हेडर भेजना होता है।

Q7. What is CORS in browser Fetch / AJAX security?

(ब्राउज़र सुरक्षा में CORS (Cross-Origin Resource Sharing) का क्या अर्थ है?)

(A) A server header mechanism controlling which external origins can read cross-domain responses

(B) A client-side image compression tool

(C) A database join syntax

(D) A JavaScript minification algorithm

Correct Answer: (A)

[EN] Browsers enforce Same-Origin Policy unless the target server sends CORS headers like Access-Control-Allow-Origin.

[HI] CORS सर्वर-आधारित अनुमति प्रणाली है जो तय करती है कि कोई बाहरी डोमेन डेटा पढ़ सकता है या नहीं।

Q8. In older XHR, what status code value 200 represents?

(AJAX/HTTP रिस्पॉन्स में status === 200 का क्या अर्थ होता है?)

(A) Not Found

(B) Internal Server Error

(C) Redirected permanently

(D) OK — the HTTP request succeeded normally

Correct Answer: (D)

[EN] HTTP 200 OK signifies successful server processing and payload delivery.

[HI] HTTP 200 OK का अर्थ है कि सर्वर ने रिक्वेस्ट को सफलतापूर्वक प्रोसेस करके सही उत्तर दिया है।

Q9. If response.json() is already called once, what happens if you call response.text() on the same Response?

(एक ही Fetch Response पर एक बार response.json() चलने के बाद फिर से response.text() चलाने पर क्या होगा?)

(A) Re-fetches from the server automatically

(B) Throws TypeError because the response body stream can only be read once (use response.clone() first)

(C) Returns null

(D) Returns raw JSON text again

Correct Answer: (B)

[EN] Response bodies are single-use ReadableStreams (response.bodyUsed turns true); clone() before reading twice.

[HI] Response स्ट्रीम केवल एक बार पढ़ी जा सकती है; दोबारा पढ़ने पर body already used की TypeError आती है।

Q10. What default HTTP method does fetch('https://api.example.com/data') use when no options object is provided?

(यदि दूसरे पैरामीटर में कोई विकल्प न दें, तो fetch(url) डिफ़ॉल्ट रूप से कौन सा HTTP मेथड इस्तेमाल करता है?)

(A) POST

(B) GET

(C) PUT

(D) HEAD

Correct Answer: (B)

[EN] fetch(url) defaults to HTTP GET unless { method: 'POST' } (or similar) is explicitly passed.

[HI] बिना विकल्प के fetch() डिफ़ॉल्ट रूप से GET रिक्वेस्ट भेजता है।

Q11. What does credentials: 'include' instruct fetch() to do?

(fetch() विकल्प में credentials: 'include' सेट करने से क्या होता है?)

(A) Disables TLS verification

(B) Sends cookies and auth headers even on cross-origin CORS requests

(C) Caches passwords in localStorage

(D) Sends data in plaintext URL query params

Correct Answer: (B)

[EN] By default fetch sends cookies on same-origin only; 'include' sends cookies cross-origin (if server allows Access-Control-Allow-Credentials).

[HI] credentials: 'include' से दूसरे डोमेन (cross-origin) की रिक्वेस्ट में भी कुकीज़ साथ भेजी जाती हैं।

Q12. Why do HTTP GET requests throw a TypeError if you attach a 'body' property inside fetch()?

(fetch() में GET रिक्वेस्ट के साथ 'body' पैरामीटर देने पर TypeError क्यों आता है?)

(A) HTTP GET and HEAD requests cannot carry a message body per Fetch specification

(B) Browsers limit GET body size to 10 bytes

(C) GET requires XML formatting

(D) body must be a binary array

Correct Answer: (A)

[EN] Parameters for GET/HEAD belong in URL query strings, not request bodies.

[HI] Fetch नियम के अनुसार GET और HEAD रिक्वेस्ट में body की अनुमति नहीं होती; डेटा URL क्वेरी स्ट्रिंग में जाता है।

Q13. Which Promise helper executes multiple independent Fetch calls concurrently and waits for ALL to succeed?

(एक साथ कई स्वतंत्र Fetch कॉल्स को समानांतर (Parallel) चलाकर सभी के पूरे होने की प्रतीक्षा किससे की जाती है?)

(A) Promise.all([...])

(B) Array.forEach(await)

(C) Promise.race([...])

(D) Promise.thenAll([...])

Correct Answer: (A)

[EN] Promise.all runs requests in parallel rather than waiting sequentially inside a for loop, dramatically lowering total load time.

[HI] Promise.all कई API कॉल्स को एक साथ समानांतर चलाकर सभी परिणाम आने पर पूरा होता है।

Q14. Which XMLHttpRequest method prepares the HTTP method and URL before calling .send()?

(XMLHttpRequest में .send() से पहले मेथड व URL सेट करने वाला मेथड कौन सा है?)

(A) xhr.connect(method, url)

(B) xhr.fetch(url)

(C) xhr.open(method, url, async)

(D) xhr.init(url)

Correct Answer: (C)

[EN] Standard XHR sequence: const xhr = new XMLHttpRequest(); xhr.open('GET', url, true); xhr.send();.

[HI] XHR में पहले xhr.open('GET', url, true) और फिर xhr.send() कॉल किया जाता है।

Q15. Which Promise method resolves with results of ALL Fetch calls even if one or more fail/reject?

(यदि कई Fetch कॉल्स में से कोई एक फेल भी हो जाए, तो भी सभी के स्टेटस (fulfilled/rejected) पाने के लिए क्या उपयोग होता है?)

(A) Promise.allSettled([...])

(B) Promise.all([...])

(C) Promise.first([...])

(D) Promise.any([...])

Correct Answer: (A)

[EN] Unlike Promise.all (which fails fast on first rejection), Promise.allSettled collects status objects for every promise.

[HI] Promise.allSettled एक रिक्वेस्ट फेल होने पर भी रुकता नहीं और सभी का परिणाम (fulfilled/rejected) देता है।

Q16. What does setting mode: 'cors' vs cache: 'no-store' in fetch() control respectively?

(fetch() के options में mode और cache प्रॉपर्टीज़ क्रमशः क्या नियंत्रित करती हैं?)

(A) Cross-origin access policy and browser HTTP caching behavior

(B) Compression ratio and SSL port

(C) Database pool and JSON parsing

(D) Thread priority and DOM events

Correct Answer: (A)

[EN] Fetch Request options include method, headers, body, mode (cors/same-origin), credentials, cache, and signal.

[HI] mode क्रॉस-ऑरिजिन सुरक्षा नियम तथा cache ब्राउज़र की HTTP कैशिंग तय करता है।

Q17. Within AJAX and Fetch API: Asynchronous HTTP Requests, which feature / property directly maps to: "Event callbacks (onreadystatechange)"?

(AJAX and Fetch API: Asynchronous HTTP Requests में कौन सा Feature / Property सीधे "Event callbacks (onreadystatechange)" से संबंधित है?)

(A) Async Pattern

(B) 404 / 500 Status

(C) Default Cookies

(D) Cancellation

Correct Answer: (A)

[EN] In AJAX and Fetch API: Asynchronous HTTP Requests, 'Async Pattern' handles 'Event callbacks (onreadystatechange)' (Promise-based (clean with async/await)).

[HI] AJAX and Fetch API: Asynchronous HTTP Requests में 'Async Pattern' का कार्य/विवरण 'Event callbacks (onreadystatechange)' (Promise-based (clean with async/await)) है।

Q18. Which option accurately describes '404 / 500 Status' in AJAX and Fetch API: Asynchronous HTTP Requests?

(AJAX and Fetch API: Asynchronous HTTP Requests के संदर्भ में '404 / 500 Status' की सही विशेषता कौन सी है?)

(A) Resolved cleanly via xhr.status check

(B) Calls xhr.abort() directly

(C) Same-origin sent automatically

(D) Event callbacks (onreadystatechange)

Correct Answer: (A)

[EN] '404 / 500 Status' provides 'Resolved cleanly via xhr.status check' — key point: Resolves! Must inspect response.ok manually.

[HI] '404 / 500 Status' का मुख्य विवरण 'Resolved cleanly via xhr.status check' है (Resolves! Must inspect response.ok manually)।

Q19. In AJAX and Fetch API: Asynchronous HTTP Requests, identify the correct parameter for the specification: "Calls xhr.abort() directly".

(AJAX and Fetch API: Asynchronous HTTP Requests में "Calls xhr.abort() directly" विवरण किस विकल्प के लिए सही है?)

(A) 404 / 500 Status

(B) Async Pattern

(C) Default Cookies

(D) Cancellation

Correct Answer: (D)

[EN] 'Cancellation' corresponds to 'Calls xhr.abort() directly' (Uses AbortController + signal option).

[HI] 'Cancellation' का संबंध 'Calls xhr.abort() directly' (Uses AbortController + signal option) से है।

Q20. Considering AJAX and Fetch API: Asynchronous HTTP Requests, what key behavior defines 'Default Cookies'?

(AJAX and Fetch API: Asynchronous HTTP Requests में 'Default Cookies' की मुख्य भूमिका या मान क्या है?)

(A) Resolved cleanly via xhr.status check

(B) Event callbacks (onreadystatechange)

(C) Calls xhr.abort() directly

(D) Same-origin sent automatically

Correct Answer: (D)

[EN] 'Default Cookies' represents 'Same-origin sent automatically' (Same-origin default (credentials: 'same-origin')).

[HI] 'Default Cookies' का अर्थ/मान 'Same-origin sent automatically' है (Same-origin default (credentials: 'same-origin'))।

AJAX and Fetch API: Asynchronous HTTP Requests — Exam FAQs

Q1: Why doesn't fetch() automatically throw inside try/catch when an API gives 404 or 500?

API से 404 या 500 आने पर भी try/catch वाला fetch एरर क्यों नहीं पकड़ता?

[EN] Because receiving a 404 or 500 HTTP response from the server means the network request itself succeeded! Always add: if (!res.ok) throw new Error(res.status).

[HI] क्योंकि सर्वर से 404 उत्तर मिलना नेटवर्क सफलता माना जाता है। इसलिए if (!res.ok) throw new Error() लिखना जरूरी है।

Q2: Is AJAX limited only to XML data?

क्या AJAX से केवल XML डेटा ही लाया जा सकता है?

[EN] No. Despite XML in its name, modern AJAX almost universally exchanges lightweight JSON (and sometimes HTML/plain text) via Fetch API.

[HI] नहीं। नाम में XML होने के बावजूद आज लगभग सभी AJAX एप्लिकेशन तेज व हल्के JSON फॉर्मेट का उपयोग करते हैं।

Q3: What is the difference between AJAX and WebSockets?

AJAX (Fetch) और WebSockets में क्या अंतर है?

[EN] AJAX/Fetch uses client-initiated HTTP request-response cycles, whereas WebSockets maintain a persistent full-duplex connection where servers can push data anytime.

[HI] AJAX क्लाइंट से रिक्वेस्ट जाने पर ही उत्तर लाता है, जबकि WebSockets में दो-तरफा स्थायी कनेक्शन बना रहता है जिससे सर्वर कभी भी डेटा पुश कर सकता है।

Related Posts

  • Loading related posts...

Post a Comment

Search Topic Notes & 20 MCQs (Hindi / English)