Skip to content

AJAX Example

Basic Asynchronous JavaScript Example (Fetch API)

Section titled “Basic Asynchronous JavaScript Example (Fetch API)”

Let’s create a very simple example to see asynchronous JavaScript in action using the modern Fetch API. We’ll load content from a text file on the server when a button is clicked.

Goal: Click a button to fetch text from message.txt and display it in a div without reloading the page.

First, set up the basic HTML elements: a div to hold the content and a button to trigger the fetch.

<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Basic Fetch Example</title>
<style>
#contentDiv {
border: 1px solid #ccc;
padding: 15px;
margin-top: 10px;
min-height: 50px;
background-color: #f9f9f9;
}
</style>
</head>
<body>
<h1>Load Content Dynamically</h1>
<button id="loadButton">Load Message</button>
<div id="contentDiv">
<p>Click the button to load content from the server.</p>
</div>
<script src="app.js"></script> <!-- Link to our JavaScript file -->
</body>
</html>

We have:

  • A button with the ID loadButton.
  • A div with the ID contentDiv where the fetched text will be displayed.
  • A script tag linking to app.js where our JavaScript code will reside.

Create a simple text file named message.txt in the same directory (or accessible via a URL path) with some content:

Hello from the server! This content was loaded asynchronously using the Fetch API.

Now, let’s write the JavaScript code to handle the button click and fetch the data.

// Get references to the button and the content div
const loadButton = document.getElementById('loadButton');
const contentDiv = document.getElementById('contentDiv');
// Define the function to fetch and display the data
async function loadMessage() {
contentDiv.innerHTML = '<p><i>Loading...</i></p>'; // Provide feedback
try {
// Use fetch to request the content from message.txt
const response = await fetch('message.txt');
// Check if the request was successful (status 200-299)
if (!response.ok) {
throw new Error(`HTTP error! Status: ${response.status}`);
}
// Get the response body as text
const messageText = await response.text();
// Update the content div with the fetched text
contentDiv.textContent = messageText;
} catch (error) {
// Handle any errors that occurred during fetch or processing
console.error('Error loading message:', error);
contentDiv.innerHTML = `<p style="color: red;">Failed to load message: ${error.message}</p>`;
}
}
// Add an event listener to the button
// When the button is clicked, call the loadMessage function
loadButton.addEventListener('click', loadMessage);
  1. Get Elements: We get references to the button and the div using their IDs.
  2. async function loadMessage(): We define an async function to contain our asynchronous logic.
  3. Loading Feedback: We immediately update the contentDiv to show a ‘Loading…’ message.
  4. fetch('message.txt'): This initiates the asynchronous HTTP GET request to the specified file.
  5. await: The await keyword pauses the loadMessage function until the fetch Promise resolves with a Response object.
  6. Error Checking (response.ok): We check if the HTTP status code indicates success. If not, we throw an error.
  7. await response.text(): If the response is ok, we await the response.text() method, which returns another Promise that resolves with the actual text content from the file.
  8. Update DOM: Once we have the messageText, we update the textContent of the contentDiv.
  9. try...catch: The entire fetching process is wrapped in a try...catch block to handle potential errors (network issues, file not found, etc.). If an error occurs, we log it and display an error message in the contentDiv.
  10. Event Listener: We attach a click event listener to the loadButton. When clicked, it executes the loadMessage function.

This example demonstrates the core principles: making an asynchronous request, handling the response (including potential errors), and updating the web page dynamically without a full reload.

The next chapters will delve deeper into configuring requests, handling different data types (like JSON), and managing asynchronous operations more effectively.