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.
HTML Structure
Section titled “HTML Structure”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
buttonwith the IDloadButton. - A
divwith the IDcontentDivwhere the fetched text will be displayed. - A
scripttag linking toapp.jswhere our JavaScript code will reside.
Server File (message.txt)
Section titled “Server File (message.txt)”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.JavaScript (app.js)
Section titled “JavaScript (app.js)”Now, let’s write the JavaScript code to handle the button click and fetch the data.
// Get references to the button and the content divconst loadButton = document.getElementById('loadButton');const contentDiv = document.getElementById('contentDiv');
// Define the function to fetch and display the dataasync 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 functionloadButton.addEventListener('click', loadMessage);Example Explained:
Section titled “Example Explained:”- Get Elements: We get references to the button and the div using their IDs.
async function loadMessage(): We define anasyncfunction to contain our asynchronous logic.- Loading Feedback: We immediately update the
contentDivto show a ‘Loading…’ message. fetch('message.txt'): This initiates the asynchronous HTTP GET request to the specified file.await: Theawaitkeyword pauses theloadMessagefunction until thefetchPromise resolves with aResponseobject.- Error Checking (
response.ok): We check if the HTTP status code indicates success. If not, we throw an error. await response.text(): If the response is ok, weawaittheresponse.text()method, which returns another Promise that resolves with the actual text content from the file.- Update DOM: Once we have the
messageText, we update thetextContentof thecontentDiv. try...catch: The entire fetching process is wrapped in atry...catchblock to handle potential errors (network issues, file not found, etc.). If an error occurs, we log it and display an error message in thecontentDiv.- Event Listener: We attach a
clickevent listener to theloadButton. When clicked, it executes theloadMessagefunction.
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.