JavaScript Fetch API and AJAX
# 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
GETrequest using thefetch()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.
---
5. Real-world Examples & Code Snippets
Example 1: Basic GET Request
Let's use a free public API (JSONPlaceholder) to get a fake user.
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).
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.
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.
Example 5: Injecting Fetched Data into the DOM
The most common use case: Fetching a list and rendering it.
---
6. Common Mistakes for Beginners
-
1.
Forgetting
.json(): Writingfetch(url).then(data => console.log(data))will just print a raw HTTP Response object. You must convert it using.then(res => res.json())first.
- 2. Assuming fetch is synchronous:
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>
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.
Write a fetch
GET request tohttps://jsonplaceholder.typicode.com/todos/1andconsole.logthe title of the todo.
-
2.
In the above request, add a .catch()
block that logs "Error occurred" if the request fails.
-
3.
Why must we use JSON.stringify()
when making aPOSTrequest 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.