JS AJAX Request
In this page:
xhr.open("GET", url, true);
xhr.send();
xhr.open("POST", url, true);
xhr.setRequestHeader("Content-type", "application/x-www-form-urlencoded");
xhr.send(data);
Passing Data via Query Parameters
For a GET request, data is typically passed as query parameters appended to the URL after a ? -- like /search?term=widgets&limit=10 -- which the server reads and parses from the incoming request's URL.
उदाहरण: Passing Data via Query Parameters
// 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));
Sending a JSON Request Body
For POST, PUT, or PATCH requests, data is usually sent in the request body as JSON -- JSON.stringify() converts a JavaScript object into that JSON string, and the Content-Type: application/json header tells the server how to correctly parse the body it receives.
उदाहरण: Sending a JSON Request Body
// 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
Sending Form Data
FormData is a built-in object that represents form-style data, including file uploads -- constructing one from an actual <form> element (or manually appending fields) and passing it directly as a fetch body sends it with the correct multipart/form-data encoding automatically, no manual Content-Type header needed.
उदाहरण: Sending Form Data
// 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));
Setting Custom Request Headers
The headers option (in fetch) or .setRequestHeader() (in XMLHttpRequest) attaches additional metadata to a request -- most commonly an Authorization header carrying an API token, letting the server verify the request came from an authenticated user.
उदाहरण: Setting Custom Request Headers
// 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
Choosing an HTTP Method
The method option specifies the HTTP verb for the request -- GET for reading data (the default), POST for creating something new, PUT or PATCH for updating, and DELETE for removing -- matching the method to the operation's actual meaning helps servers and any caching layers behave correctly.
उदाहरण: Choosing an HTTP Method
fetch("delete.php", { method: "DELETE" }).then(r => console.log(r.status));
fetch("update.php", { method: "PUT" }).then(r => console.log(r.status));
Chapter Quiz — Complete all 26 topics to unlock
0/26 topics done
Complete these topics first:
- JS JSON
- JS Regular Expressions
- JS Fetch API
- JS LocalStorage and SessionStorage
- JS Cookies
- JS setTimeout and setInterval
- JS Event Loop
- JS Web Workers
- JS Service Workers
- JS AJAX
- JS AJAX Intro
- JS AJAX XMLHttp
- JS AJAX Request
- JS AJAX Response
- JS AJAX XML
- JS AJAX PHP
- JS AJAX Database
- JS JSONP
- JS RegExp Flags
- JS RegExp Classes
- JS RegExp Metachars
- JS RegExp Assertions
- JS RegExp Groups
- JS RegExp Quantifiers
- JS JSON HTML
- JS JSON vs XML