fbpx

AJAX (Asynchronous JavaScript and XML) and Fetch API

AJAX is a set of web development techniques used to create asynchronous web applications. It enables data to be retrieved from a server asynchronously in the background, without interfering with the display and behavior of the existing page. The Fetch API is a modern replacement for the older XMLHttpRequest and provides a more powerful and flexible interface for making HTTP requests. Let’s explore both AJAX and the Fetch API:

AJAX (Asynchronous JavaScript and XML):

1. XMLHttpRequest:

  • Traditionally, AJAX was implemented using the XMLHttpRequest object.
   const xhr = new XMLHttpRequest();
   xhr.open('GET', 'https://api.example.com/data', true);
   xhr.onreadystatechange = function() {
       if (xhr.readyState === 4 && xhr.status === 200) {
           const data = JSON.parse(xhr.responseText);
           console.log(data);
       }
   };
   xhr.send();

2. jQuery AJAX:

  • jQuery simplifies AJAX calls with its $.ajax function.
   $.ajax({
       url: 'https://api.example.com/data',
       method: 'GET',
       success: function(data) {
           console.log(data);
       },
       error: function(error) {
           console.error(error);
       }
   });

Fetch API:

1. Basic Fetch:

  • The Fetch API provides a cleaner and more powerful way to make HTTP requests.
   fetch('https://api.example.com/data')
       .then(response => {
           if (!response.ok) {
               throw new Error('Network response was not ok');
           }
           return response.json();
       })
       .then(data => console.log(data))
       .catch(error => console.error(error));

2. Headers and Request Methods:

  • Specify request methods and headers easily with the Fetch API.
   const requestOptions = {
       method: 'POST',
       headers: {
           'Content-Type': 'application/json',
           'Authorization': 'Bearer YOUR_ACCESS_TOKEN'
       },
       body: JSON.stringify({ key: 'value' })
   };

   fetch('https://api.example.com/postData', requestOptions)
       .then(response => response.json())
       .then(data => console.log(data))
       .catch(error => console.error(error));

3. Async/Await with Fetch:

  • Utilize async/await for cleaner asynchronous code.
   async function fetchData() {
       try {
           const response = await fetch('https://api.example.com/data');
           if (!response.ok) {
               throw new Error('Network response was not ok');
           }
           const data = await response.json();
           console.log(data);
       } catch (error) {
           console.error(error);
       }
   }

   fetchData();

4. Abort Controller:

  • Use the AbortController to cancel a fetch request.
   const controller = new AbortController();
   const signal = controller.signal;

   setTimeout(() => controller.abort(), 5000);

   fetch('https://api.example.com/data', { signal })
       .then(response => response.json())
       .then(data => console.log(data))
       .catch(error => console.error(error));

5. Cross-Origin Requests and CORS:

  • Fetch handles CORS (Cross-Origin Resource Sharing) transparently.
   fetch('https://api.example.com/data')
       .then(response => response.json())
       .then(data => console.log(data))
       .catch(error => console.error(error));

Conclusion:

Both AJAX and the Fetch API play crucial roles in making asynchronous requests and handling data in web applications. While AJAX has been widely used in the past and can still be found in legacy codebases, the Fetch API offers a more modern and cleaner approach to handling HTTP requests. When building new applications or updating existing ones, consider using the Fetch API for its simplicity, Promises, and integration with modern JavaScript features like async/await.