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

JS AJAX रिक्वेस्ट

एक साधारण GET से आगे, एक AJAX request को अक्सर server तक data ले जाना होता है -- filtering के लिए query parameters, कोई record बनाने के लिए एक JSON body, authentication के लिए custom headers -- और request पर इन्हें सही तरीके से configure करना server द्वारा सही ढंग से समझे और process किए जाने के लिए ज़रूरी है।
Syntax
javascript
xhr.open("GET", url, true);
xhr.send();

xhr.open("POST", url, true);
xhr.setRequestHeader("Content-type", "application/x-www-form-urlencoded");
xhr.send(data);

Query Parameters से Data पास करना

एक GET request के लिए, data आमतौर पर URL के ? के बाद जोड़े गए query parameters के रूप में पास किया जाता है -- जैसे /search?term=widgets&limit=10 -- जिसे server आती हुई request के URL से पढ़ता और parse करता है।

Note: & और = से manually strings को concatenate करने के बजाय, जिसमें गलती होना आसान है, एक query string safely बनाने के लिए URLSearchParams इस्तेमाल करें।
Warning: किसी & या = character वाली एक raw, un-encoded value को सीधे किसी query string में डालना URL की structure को बिगाड़ देगा।

उदाहरण: Passing Data via Query Parameters

javascript
// Declare the constant `term`, set to "widgets"
// Declare the constant `term`, set to "widgets"
const term = "widgets";
// Declare the constant `limit`, set to `10`
// Declare the constant `limit`, set to `10`
const limit = 10;
// Define the method `fetch` taking ``search.php?term`
fetch(`search.php?term=${term}&limit=${limit}`)
  // 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 => console.log(data));

एक JSON Request Body भेजना

POST, PUT, या PATCH requests के लिए, data आमतौर पर request body में JSON के रूप में भेजा जाता है -- JSON.stringify() किसी JavaScript object को उस JSON string में बदल देता है, और Content-Type: application/json header server को बताता है कि उसे मिली body को सही तरीके से कैसे parse करना है।

Note: body में JSON.stringify() को हमेशा एक Content-Type: application/json header के साथ जोड़ें -- उस header के बिना JSON भेजना कुछ servers को body को गलत समझने पर मजबूर कर सकता है।
Warning: JSON.stringify() कॉल करना भूल जाना और किसी raw JavaScript object को सीधे body के रूप में भेजना असली JSON data के बजाय बेकार text "[object Object]" भेजता है।

उदाहरण: Sending a JSON Request Body

javascript
// Send a POST request with a JSON body to save.php
fetch("save.php", {
  method: "POST",
  headers: { "Content-Type": "application/json" }, // tell the server we're sending JSON
  body: JSON.stringify({ name: "Sam" }), // convert the JS object into a JSON string
}).then(r => r.json()).then(data => console.log(data)); // parse and log the server's JSON reply

Form Data भेजना

FormData एक built-in object है जो form-style data को represent करता है, file uploads सहित -- इसे किसी असली <form> element से बनाना (या manually fields जोड़ना) और इसे सीधे fetch body के रूप में पास करना अपने आप सही multipart/form-data encoding के साथ भेज देता है, किसी manual Content-Type header की ज़रूरत नहीं।

Note: FormData भेजते समय browser को Content-Type header अपने आप सेट करने दें -- इसे manually सेट करना असल में ज़रूरी boundary parameter छोड़कर request को तोड़ सकता है।
Warning: जब भी किसी request में असली file upload शामिल करना हो, तो FormData (JSON के बजाय) ज़रूरी है, क्योंकि JSON binary file data represent नहीं कर सकता।

उदाहरण: Sending Form Data

javascript
// Declare the constant `formData` as a new `FormData` instance
// Declare the constant `formData` as a new `FormData` instance
const formData = new FormData();
// Call `formData.append("name", "Sam")`
// Call `formData.append("name", "Sam")`
formData.append("name", "Sam");
// Define the method `fetch` taking `"upload.php"`, `{ method: "POST", body: formData }`
// Define the method `fetch` taking `"upload.php"`, `{ method: "POST", body: formData }`
fetch("upload.php", { method: "POST", body: formData })
  // On success, run this with the resolved value as `r`
  // On success, run this with the resolved value as `r`
  .then(r => r.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(data));

Custom Request Headers सेट करना

headers option (fetch में) या .setRequestHeader() (XMLHttpRequest में) किसी request में अतिरिक्त metadata जोड़ता है -- सबसे आम तौर पर एक API token ले जाने वाला Authorization header, जो server को यह verify करने देता है कि request किसी authenticated user से आई।

Note: जब संभव हो, sensitive tokens (जैसे कोई API key) को अपने client-side JavaScript source के बाहर रखें, क्योंकि browser को भेजी गई कोई भी चीज़ page को inspect करने वाले किसी को भी दिखती है।
Warning: कुछ headers (जैसे Origin या Host) protected हैं और security कारणों से JavaScript द्वारा manually सेट नहीं किए जा सकते, चाहे उन्हें कैसे भी specify किया जाए।

उदाहरण: Setting Custom Request Headers

javascript
// Send a GET request to data.php with a Bearer auth token
fetch("data.php", {
  headers: { "Authorization": "Bearer sample-token" }, // proves who is making the request
}).then(r => r.json()).then(data => console.log(data)); // parse and log the JSON reply

एक HTTP Method चुनना

method option किसी request के लिए HTTP verb बताता है -- data पढ़ने के लिए GET (default), कुछ नया बनाने के लिए POST, update करने के लिए PUT या PATCH, और हटाने के लिए DELETE -- method को operation के असली मतलब से मिलाना servers और किसी caching layers को सही व्यवहार करने में मदद करता है।

Note: हर चीज़ के लिए GET या POST को default बनाने के बजाय, अपनी request के method को उसके असली semantic मकसद (reads के लिए GET, creates के लिए POST, वगैरह) से मिलाएं।
Warning: Browsers और proxies GET requests को आक्रामक रूप से cache कर सकते हैं -- server state को असल में बदलने वाले किसी operation के लिए GET इस्तेमाल करना confusing, असंगत caching व्यवहार दे सकता है।

उदाहरण: Choosing an HTTP Method

javascript
fetch("delete.php", { method: "DELETE" }).then(r => console.log(r.status));
fetch("update.php", { method: "PUT" }).then(r => console.log(r.status));
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. भेजे जा रहे data के असली format से match करने के लिए Content-Type header set करना भूल जाना, जिससे server request body को गलत समझता है या reject कर देता है।
  2. query parameters को गलत तरीके से URL-encode करना (या बिल्कुल न करना), जो किसी value में & या spaces जैसे special characters होने पर URL को तोड़ सकता है।
  3. किसी GET request पर एक request body भेजना, जो HTTP convention के खिलाफ है और अक्सर servers और कुछ HTTP client implementations द्वारा नजरअंदाज या reject कर दिया जाता है।
चैप्टर सारांश
  • GET requests data को URL query parameters के ज़रिए pass करते हैं; POST/PUT requests आमतौर पर data को request body में pass करते हैं।
  • Content-Type header server को बताता है कि request body के format (JSON, form-encoded, आदि) को कैसे समझा जाए।
  • encodeURIComponent() किसी value को URL में डालने से पहले उसके special characters को safely escape करता है।
ब्राउज़र सपोर्ट

headers, query parameters, और body के साथ requests configure करना fetch और XMLHttpRequest दोनों के ज़रिए हर modern browser में समान रूप से 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.