6.5. Basics of JavaScript: Asynchronous Network Requests with AJAX/Fetch

 

AJAX (Asynchronous JavaScript and XML)

What is AJAX?

AJAX is a technology that allows a web page to exchange data with a server without the need to reload the entire page. With AJAX, you can send requests to the server and receive updated data without interrupting the user's interaction with the page.

Example of AJAX: Imagine you have a web page with a "Load Information" button, and you want to retrieve textual information from the server without reloading the page.

Here is the HTML file:

<html>     <head>          <title>AJAX</title>     </head>     <body>         <button id="download">Load Information</button>         <div id="result"></div>         <script src="/ajax.js"></script>     </body></html>

 

And here is the JavaScript file (ajax.js):

// Find elements on the pagelet downloadButton = document.getElementById("download");let result = document.getElementById("result");
// Add an event handler to the buttondownloadButton.addEventListener("click", function() {
      // Create an object for making the request      let requestToServer = new XMLHttpRequest();
     // Configure the request      requestToServer.open("GET", "server/path/to/information.txt", true);
     // Set an event handler for when the request is completed     requestToServer.onload = function() {        if (requestToServer.status >= 200 && requestToServer.status < 400) {
        // Update the content on the page        result.textContent = requestToServer.responseText;        } else {           result.textContent = "Error loading data.";       }  };
  // Send the request  requestToServer.send();});

AJAX allows for dynamic data retrieval and updating without the need for page reloads, enhancing the user experience on web applications.

 

Fetch

What is Fetch?

Fetch is a modern standard for making network requests in the browser. It provides a more convenient and flexible interface for working with requests and responses.

Fetch Example: The example is similar to AJAX, but the JavaScript code is implemented differently. The script will fetch JSON data from a remote server.

HTML file:

<html>    <head>        <title>Fetch</title>   </head>   <body>       <button id="download">Download Information</button>       <div id="result"></div>       <script src="/fetch.js"></script>   </body></html>

 

JavaScript (fetch.js):

// Find elements on the pagelet downloadButton = document.getElementById("download");let result = document.getElementById("result");
// Add an event handler to the buttondownloadButton.addEventListener("click", function() {
  // Send a GET request using Fetch  fetch("server/path/to/data.json")    .then(response => response.json())    .then(data => {
      // Update the content on the page      result.textContent = "Name: " + data.name + ", Age: " + data.age;    })    .catch(error => {      result.textContent = "Error loading data.";    });});

In this example, we use the Fetch API to send a GET request and receive JSON data from the server. The received data is processed and displayed on the page.

Both AJAX and Fetch technologies allow you to interact with the server and update the content of web pages without reloading. Fetch is a more modern and convenient way to make network requests, but both methods can be useful in different scenarios.