JavaScript ยท Chapter 53 of 55

JavaScript Fetch & AJAX

AJAX (Asynchronous JavaScript and XML) lets a web page fetch data from a server without reloading. The modern `fetch()` API is the standard tool for making these network requests.

`fetch(url)` returns a Promise that resolves to a Response object; you typically call `.json()` on it to parse the body, often combined with async/await for readability.

Basic fetch usage

`fetch('https://api.example.com/data').then(res => res.json()).then(data => console.log(data))` retrieves and parses JSON data from an API.

fetch with async/await

`const res = await fetch(url); const data = await res.json();` reads more linearly and pairs well with try/catch for error handling.

Example 1 (javascript)
fetch("https://api.example.com/users/1")
  .then(res => res.json())
  .then(data => console.log(data.name));
Output
(depends on API response)

fetch retrieves data, then .json() parses the response body.

Example 2 (javascript)
async function getUser() {
  try {
    const res = await fetch("https://api.example.com/users/1");
    const data = await res.json();
    console.log(data.name);
  } catch (err) {
    console.log("Request failed:", err.message);
  }
}
Output
(depends on API response)

async/await version with error handling via try/catch.

Key points

  • fetch() sends an HTTP request and returns a Promise.
  • res.json() parses the response body as JSON, returning another Promise.
  • fetch pairs naturally with async/await for readable code.
  • Always handle errors โ€” fetch only rejects on network failure, not HTTP error status codes.
๐Ÿ’ก Note: fetch() does NOT reject on 404 or 500 responses โ€” check res.ok or res.status explicitly to detect HTTP errors.

๐Ÿ“ Quick Quiz

1. What does fetch() return?

2. Which method parses a fetch response as JSON?

3. Does fetch reject on a 404 response?