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.

JavaScript8 min readConcept 35 of 62

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

// 1. Fire request (Promise 1)
fetch("/api/user")
.then(response => {
// 2. The crucial HTTP check
if (!response.ok) {
throw new Error("HTTP Error");
}
// 3. Unwrap body (Promise 2)
return response.json();
})
.then(data => {
console.log(data);
})
.catch(err => {
console.error(err);
});
fetch("/api/user")
IDLE
Response Headers Arrived
WAITING...
response.json()
STANDBY
.catch()
STANDBY
iWhen simulating a 404, notice that the first Promise still fulfills! The Response object arrives successfully, but we manually throw an error because response.ok is false.

Check yourself

Pick an answer to lock it in, then read why. Getting one wrong is part of how it sticks.

  1. 1Why do you have to call `response.json()` instead of just reading the data immediately from the `response` object?
  2. 2If your `fetch` request receives a `500 Internal Server Error`, what happens to the Promise?
  3. 3What does `response.ok` do?

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.