JS AJAX Intro
In this page:
The Request/Response Cycle
An AJAX interaction has three stages: your JavaScript code initiates a request (specifying a URL and optional data), the browser sends it to the server and waits in the background, and once a response arrives, your registered callback or promise handler processes it.
उदाहरण: The Request/Response Cycle
// Define the method `fetch` taking `"data.php"`
// Define the method `fetch` taking `"data.php"`
fetch("data.php")
// On success, run this with the resolved value as `response`
// On success, run this with the resolved value as `response`
.then(response => response.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("Response handled:", data));
Why AJAX Requests Are Asynchronous
A network request to a server can take anywhere from milliseconds to several seconds, depending on the server and connection -- if JavaScript waited (blocked) for every request to finish before continuing, the entire page would freeze and become unresponsive during that wait, which is exactly what asynchronous requests avoid.
उदाहरण: Why AJAX Requests Are Asynchronous
console.log("Request started");
fetch("data.php").then(r => r.json()).then(data => console.log("Response arrived:", data));
console.log("Page stays responsive while waiting"); // logs before the fetch resolves
Same-Origin Policy and CORS
By default, a browser blocks JavaScript from making an AJAX request to a different origin (domain, protocol, or port) than the page itself, as a security measure -- a server can explicitly opt in to allow cross-origin requests by sending CORS (Cross-Origin Resource Sharing) response headers.
उदाहरण: Same-Origin Policy and CORS
fetch("data.php").then(r => r.json()).then(data => console.log(data));
// Cross-origin requests need the server to send CORS headers to be allowed
Handling Success and Failure
A well-built AJAX interaction plans for both outcomes: a successful response that updates the page, and a failed request (network error, timeout, or server error) that shows the user a clear message instead of leaving them staring at a stuck loading state.
उदाहरण: Handling Success and Failure
// Define the method `fetch` taking `"data.php"`
// Define the method `fetch` taking `"data.php"`
fetch("data.php")
// On success, run this with the resolved value as `response`
// On success, run this with the resolved value as `response`
.then(response => {
if (!response.ok) throw new Error("Request failed");
// Return `response.json()` from this function
// Return `response.json()` from this function
return response.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("Success:", data))
// On failure, run this with the error as `error`
// On failure, run this with the error as `error`
.catch(error => console.log("Show user a message:", error.message));
A Complete Beginner AJAX Example
Combining everything from this introduction: a button click initiates a request, the page shows a loading state while waiting, and the response (success or failure) updates the page -- the complete, minimal shape every AJAX interaction follows, regardless of how complex the actual application logic becomes.
उदाहरण: A Complete Beginner AJAX Example
<button id="loadBtn">Load Data</button>
<p id="status">Idle</p>
<script>
document.getElementById("loadBtn").addEventListener("click", () => {
document.getElementById("status").textContent = "Loading...";
// Define the method `fetch` taking `"data.php"`
fetch("data.php")
// 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 => document.getElementById("status").textContent = "Loaded: " + data.message)
.catch(() => document.getElementById("status").textContent = "Failed");
});
</script>
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