Skip to main content
JavaScript Basics
CHAPTER 24 Beginner

JavaScript Fetch API and AJAX

Updated: May 12, 2026
30 min read

# JavaScript Fetch API and AJAX

In the early days of the internet, if you wanted to load new data—like seeing the next page of a forum or submitting a comment—your browser had to refresh the entire page.

Today, web apps feel like native mobile apps. They load data instantly in the background without refreshing. This magic is called AJAX, and in modern JavaScript, it is powered by the Fetch API.

1. Introduction

AJAX stands for Asynchronous JavaScript And XML. It is not a programming language, but a concept: the ability of JavaScript to make HTTP requests (talk to a server) in the background while the user continues interacting with the page.

Historically, this was done using a clunky tool called XMLHttpRequest. Modern JavaScript introduced fetch(), which provides a much cleaner, promise-based way to make web requests.

2. Learning Objectives

By the end of this chapter, you will be able to:

  • Understand the concept of Asynchronous programming (Promises).
  • Make a GET request using the fetch() API.
  • Handle JSON responses from a server.
  • Catch and handle network errors.
  • Build a working Weather App mini-project using a public API.

3. The Concept of Promises

When you ask a server for data, it doesn't arrive instantly. It might take 50 milliseconds, or 5 seconds if the internet is slow.

JavaScript doesn't wait around. It returns a Promise. A Promise is exactly what it sounds like: "I promise I will give you the data when it arrives, but for now, keep running the rest of the code."

You handle a promise using .then() (what to do when the data arrives) and .catch() (what to do if the server crashes).

4. The fetch() Syntax

The fetch() function takes one mandatory argument: the URL you want to get data from. It returns a Promise.

javascript
1234567891011
// Syntax
fetch('https://api.example.com/data')
  .then(response => response.json()) // 1. Convert network response to JSON
  .then(data => {
      // 2. Do something with the actual data
      console.log(data);
  })
  .catch(error => {
      // 3. Handle any errors
      console.error(error);
  });

---

5. Real-world Examples & Code Snippets

Example 1: Basic GET Request

Let's use a free public API (JSONPlaceholder) to get a fake user.

javascript
1234567
// Example JavaScript
fetch('https://jsonplaceholder.typicode.com/users/1')
  .then(response => response.json()) // Parse the JSON string from the server
  .then(user => {
      console.log("User Name: " + user.name);
      console.log("User Email: " + user.email);
  });

Example 2: Checking the Response Status

Sometimes the server is online, but the data doesn't exist (e.g., a 404 Error). fetch() only rejects a promise on a total network failure. You must manually check if the HTTP status is "OK" (200).

javascript
12345678910
// Example JavaScript
fetch('https://jsonplaceholder.typicode.com/users/999') // User 999 doesn't exist!
  .then(response => {
      if (!response.ok) {
          throw new Error(`HTTP error! Status: ${response.status}`);
      }
      return response.json();
  })
  .then(data => console.log(data))
  .catch(error => console.log("Caught an error: " + error.message));

Example 3: Handling Network Failures (.catch)

If the user's WiFi drops, or the server is completely dead, .catch() intercepts the failure so your app doesn't crash.

javascript
12345678
// Example JavaScript
fetch('https://this-website-does-not-exist.com')
  .then(res => res.json())
  .then(data => console.log(data))
  .catch(error => {
      // Display a nice UI message to the user
      document.getElementById("alert").innerHTML = "Network disconnected. Check your internet.";
  });

Example 4: Making a POST Request

fetch() defaults to a GET request (reading data). If you want to send data (like submitting a form), you must configure fetch() for a POST request.

javascript
12345678910111213141516
// Example JavaScript
const newPost = {
    title: "My JS Course",
    body: "Learning fetch is fun!",
    userId: 1
};

fetch('https://jsonplaceholder.typicode.com/posts', {
    method: 'POST', // Change method
    headers: {
        'Content-Type': 'application/json' // Tell server we are sending JSON
    },
    body: JSON.stringify(newPost) // Serialize our JS object!
})
.then(response => response.json())
.then(data => console.log("Successfully saved with ID:", data.id));

Example 5: Injecting Fetched Data into the DOM

The most common use case: Fetching a list and rendering it.

html
12
<!-- Example HTML -->
<ul id="userList">Loading users...</ul>
javascript
123456789101112
// Example JavaScript
fetch(&#039;https://jsonplaceholder.typicode.com/users')
  .then(res => res.json())
  .then(usersArray => {
      const list = document.getElementById("userList");
      list.innerHTML = ""; // Clear the 'loading' text
      
      // Loop through array and build HTML
      usersArray.forEach(user => {
          list.innerHTML += `<li>${user.name} (${user.company.name})</li>`;
      });
  });

---

6. Common Mistakes for Beginners

  1. 1. Forgetting .json(): Writing fetch(url).then(data => console.log(data)) will just print a raw HTTP Response object. You must convert it using .then(res => res.json()) first.
  1. 2. Assuming fetch is synchronous:
javascript
12345678910111213141516
   let myData;
   fetch(url).then(res => res.json()).then(data => { myData = data; });
   console.log(myData); // UNDEFINED!
   ```
   JavaScript does not wait for the fetch to finish. The `console.log` runs instantly, before the data arrives. All logic requiring the data MUST happen inside the `.then()`.

## 7. Best Practices

- Always include a `.catch()` block. Users will experience internet drops, and unhandled promises can crash modern apps.
- Always check `!response.ok` immediately after the fetch to handle 404s and 500s properly.

## 8. Mini Project: Random Dog Image Fetcher

Let&#039;s use a free public API to fetch a random picture of a dog every time the user clicks a button.

**HTML:**

html <!-- Example HTML --> <!DOCTYPE html> <html> <head> <style> /* Example CSS */ body { font-family: sans-serif; text-align: center; padding: 20px; background: #e0e0e0;} .card { background: white; padding: 20px; border-radius: 8px; box-shadow: 0 4px 8px rgba(0,0,0,0.2); display: inline-block; width: 300px; min-height: 350px;} img { width: 100%; border-radius: 4px; margin-top: 15px; height: 250px; object-fit: cover; background: #ccc;} button { background: #007bff; color: white; border: none; padding: 12px 20px; cursor: pointer; border-radius: 4px; font-size: 16px; width: 100%;} .loader { display: none; margin-top: 15px; font-style: italic; color: #555;} </style> </head> <body>

<div class="card"> <h2>Dog Generator</h2> <button onclick="getDog()">Fetch Dog!</button> <p class="loader" id="loader">Fetching from server...</p> <img id="dogImg" src="" alt="Dog image will appear here"> </div>

<script src="fetcher.js"></script> </body> </html>

1
**fetcher.js:**

javascript // Example JavaScript function getDog() { const imgElement = document.getElementById("dogImg"); const loader = document.getElementById("loader"); // Show loading state loader.style.display = "block"; imgElement.style.opacity = "0.5";

// 1. Call the public API fetch('https://dog.ceo/api/breeds/image/random') // 2. Parse the network response to JSON .then(response => { if (!response.ok) throw new Error("Network response was not ok"); return response.json(); }) // 3. Handle the data (The API returns { message: "image_url", status: "success" }) .then(data => { // Update the image source imgElement.src = data.message; // Hide loading state loader.style.display = "none"; imgElement.style.opacity = "1"; }) // 4. Handle errors .catch(error => { loader.innerHTML = "Failed to fetch dog. Try again."; loader.style.color = "red"; console.error("Error:", error); }); }

// Fetch one immediately when page loads getDog(); ``

9. Exercises

  1. 1. Write a fetch GET request to https://jsonplaceholder.typicode.com/todos/1 and console.log the title of the todo.
  1. 2. In the above request, add a .catch() block that logs "Error occurred" if the request fails.
  1. 3. Why must we use JSON.stringify() when making a POST request with a JavaScript object?

10. MCQs (Multiple Choice Questions)

Q1: What does AJAX allow you to do? A) Write CSS directly in JavaScript. B) Connect to a MySQL database directly from the browser. C) Load data from a server without refreshing the entire web page. D) Parse XML files into HTML. *Answer: C*

Q2: What is the mandatory first argument for the fetch() function? A) The method (GET/POST) B) The URL to fetch from C) The data payload D) A callback function *Answer: B*

Q3: What does fetch() return immediately? A) The JSON data B) An HTML string C) A Promise D) An Error *Answer: C*

11. Interview Questions

Q: What is a Promise in JavaScript? *A: A Promise is an object representing the eventual completion (or failure) of an asynchronous operation. It has three states: Pending (waiting), Fulfilled (success), or Rejected (failed).*

Q: If a fetch() request returns a 404 Not Found error, will the .catch() block execute? *A: No. fetch() only rejects the promise (triggering .catch()) if there is a network-level failure, such as the server being completely unreachable or the user being offline. A 404 is considered a successful HTTP response. You must manually check response.ok to handle 404s.*

12. FAQs

Q: Do I still need to learn XMLHttpRequest? *A: No. Unless you are maintaining a very old legacy codebase (written before 2015), fetch() has entirely replaced XMLHttpRequest.*

13. Summary

  • AJAX allows background data loading.
  • fetch(url) is the modern way to make HTTP requests.
  • It returns a Promise. Use .then() to handle success.
  • Convert responses using res.json().
  • Use .catch()` to handle network failures.
  • For POST requests, specify the method, headers, and stringify the body.

14. Next Chapter Recommendation

Fetching data is great, but what if the user closes the tab? They lose everything! To save data permanently on the user's computer, we need storage. In the next chapter, JavaScript Local Storage and Session Storage, we will learn how to build apps that remember users even after they leave the website.

Finish this Chapter

Save your progress on your learning path and prepare for coding interview challenges.

Discussion

Join the discussion

Log in or create a free account to participate.

Sort: ·