The Front-End
JavaScript
AJAX and Fetch API

AJAX and Fetch API: Making Asynchronous Requests and Handling Data

  1. AJAX (Asynchronous JavaScript and XML)
  2. Fetch API
  3. Handling Data from APIs

AJAX (Asynchronous JavaScript and XML)

AJAX is a technology that enables web pages to update dynamically by exchanging data with a server behind the scenes. It allows for asynchronous communication, meaning the browser can request data from a server without reloading the entire page.

Example using XMLHttpRequest:

// Creating an XMLHttpRequest object
var xhr = new XMLHttpRequest();
 
// Configuring the request
xhr.open("GET", "https://jsonplaceholder.typicode.com/todos/1", true);
 
// Handling the response
xhr.onload = function () {
  if (xhr.status == 200) {
    var data = JSON.parse(xhr.responseText);
    console.log(data);
  } else {
    console.error("Error:", xhr.statusText);
  }
};
 
// Sending the request
xhr.send();

Fetch API

The Fetch API is a modern replacement for XMLHttpRequest, providing a more powerful and flexible way to make asynchronous requests. It returns Promises, making it easier to work with asynchronous code.

Making a GET request with Fetch:

// Making a GET request using Fetch
fetch("https://jsonplaceholder.typicode.com/todos/1")
  .then(response => {
    if (!response.ok) {
      throw new Error(`HTTP error! Status: ${response.status}`);
    }
    return response.json();
  })
  .then(data => {
    console.log(data);
  })
  .catch(error => {
    console.error("Error:", error);
  });

Making a POST request with Fetch:

// Making a POST request using Fetch
fetch("https://jsonplaceholder.typicode.com/posts", {
  method: "POST",
  headers: {
    "Content-Type": "application/json",
  },
  body: JSON.stringify({
    title: "foo",
    body: "bar",
    userId: 1,
  }),
})
  .then(response => response.json())
  .then(data => {
    console.log("Post created:", data);
  })
  .catch(error => {
    console.error("Error:", error);
  });

The Fetch API provides a cleaner and more modern syntax for making HTTP requests. It supports various HTTP methods, headers, and request/response transformations.

Handling Data from APIs

Once you've made a successful request to an API, you'll often need to handle and use the returned data. In the examples above, the data is handled in the .then() block of the Promises.

Example: Displaying Data in HTML

// Displaying data in HTML
fetch("https://jsonplaceholder.typicode.com/todos/1")
  .then(response => response.json())
  .then(data => {
    // Assuming there is an element with the id "result" in the HTML
    document.getElementById("result").innerHTML = `<p>Title: ${data.title}</p><p>Completed: ${data.completed}</p>`;
  })
  .catch(error => {
    console.error("Error:", error);
  });

In this example, the data from the API response is used to dynamically update the content of an HTML element with the id "result."

Understanding how to make asynchronous requests with Fetch, handle data from APIs, and update the UI dynamically is crucial for building modern and interactive web applications. AJAX and the Fetch API play a significant role in enabling these capabilities and are widely used in web development.