# 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.

Subject: JavaScript | Lesson 35 of 63 | 8 min read
Interactive lesson: https://codewithanimation.in/javascript/fetch-and-ajax
Previous: [Promise Combinators](https://codewithanimation.in/javascript/promise-combinators.md) | Next: [Web Storage: localStorage, cookies & IndexedDB](https://codewithanimation.in/javascript/web-storage.md)

## 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()`.

## Common mistake: The 404 Trap

The biggest trap in JavaScript network requests is that `fetch()` **does not reject on HTTP errors**.

If the server returns a `404 Not Found` or a `500 Internal Server Error`, the `fetch` Promise still *fulfills*. It only rejects on total network failures (like being offline).

This is why you must manually throw an error if `response.ok` is false, otherwise your `.catch()` block will never run for server errors!

## Tip: Sending Data

By default, `fetch` makes a `GET` request. To send data, you must pass a configuration object as the second argument: `{ method: 'POST', body: JSON.stringify(data), headers: { 'Content-Type': 'application/json' } }`.

## Try it: 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 animation is on the lesson page and is not part of this text version: https://codewithanimation.in/javascript/fetch-and-ajax

## Check yourself

### Question 1

Why do you have to call `response.json()` instead of just reading the data immediately from the `response` object?

- A. Because the first Promise only resolves when the headers arrive; the body might still be downloading.
- B. Because JSON is a secure format that requires cryptographic unwrapping.
- C. Because `response` is an array.

Correct answer: A

Network streams take time. The browser gives you the `Response` object immediately so you can check headers and status codes, but you must wait on a second Promise (`.json()`) to get the full downloaded body.

- Why not B: Incorrect. It's just plain text being parsed into objects.
- Why not C: Incorrect. `response` is an instance of the Response Web API object.

### Question 2

If your `fetch` request receives a `500 Internal Server Error`, what happens to the Promise?

- A. The Promise fulfills successfully.
- B. The Promise rejects immediately.
- C. The Promise stays pending forever.

Correct answer: A

The `fetch` Promise only rejects if there is a literal network failure (like a disconnected router). A `500` error is technically a successful HTTP conversation between the client and server, so the Promise fulfills. You must manually check `response.ok`.

- Why not B: Incorrect. This is the biggest gotcha in the Fetch API!
- Why not C: Incorrect. The server responded, so the Promise settles.

### Question 3

What does `response.ok` do?

- A. It returns `true` if the HTTP status code is between 200 and 299.
- B. It returns `true` if the JSON parsed without syntax errors.
- C. It returns a Promise.

Correct answer: A

`response.ok` is a convenience property that saves you from writing `if (response.status >= 200 && response.status < 300)`.

- Why not B: Incorrect. It only checks the HTTP status code headers.
- Why not C: Incorrect. It is a synchronous boolean property.

## 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.
