Fetch, AJAX & HTTP
Learn how JavaScript communicates with servers. Master the modern fetch API, handle HTTP errors correctly, and understand how the browser processes JSON responses.
The Backbone of Web Apps
AJAX (Asynchronous JavaScript and XML) is the concept of fetching data from a server in the background and updating the page without triggering a full page reload.
Today, the modern standard for AJAX is the fetch() API, which is built on top of Promises.
The Two-Step Promise
When you call fetch(url), it returns a Promise. But there is a catch: that first Promise only resolves when the *headers* of the response arrive.
The actual data (the body) might still be downloading. Because of this, the Response object gives you methods like .json() and .text() - which return a *second* Promise that resolves only when the full body is finished downloading and parsing.
The Fetch Boilerplate
A standard modern fetch request looks like this:
1. Call fetch(url).
2. Check if (!response.ok) to ensure the HTTP status code is in the 200-299 range.
3. Return response.json() to parse the data.
4. Handle the final data in the next .then().
The Fetch Flow
Click 'Fire Request' to see the two-step nature of the fetch API. Toggle 'Simulate 404' to see why the manual response.ok check is absolutely critical.
The Fetch Flow
fetch("/api/user")
if (!response.ok) {
throw new Error("HTTP Error");
}
return response.json();
console.log(data);
})
console.error(err);
});
Check yourself
Pick an answer to lock it in, then read why. Getting one wrong is part of how it sticks.
Remember this
- AJAX allows background network requests without page reloads.
- The modern
fetch()API is built on Promises. fetch()returns a Promise that resolves when the response headers arrive.response.json()returns a second Promise that resolves when the data finishes downloading.fetch()does not reject on HTTP errors like 404 or 500.- You must manually check
if (!response.ok) throw new Error()to handle server errors.
Done with this concept?
Mark it complete to track your progress. No login needed.