Using XMLHttpRequest and Fetch API for Ajax Requests

Intermediate

๐ŸŒ Ajax Interfaces: XMLHttpRequest vs. Fetch API

Modern web development primarily utilizes two interfaces for Ajax requests: XMLHttpRequest and the Fetch API.


๐Ÿงพ XMLHttpRequest

var xhr = new XMLHttpRequest();
xhr.open('GET', 'data.json', true);
xhr.onload = function() {
  if (xhr.status === 200) {
    var data = JSON.parse(xhr.responseText);
    console.log(data);
  }
};
xhr.send();

๐Ÿงผ Fetch API

fetch('data.json')
  .then(response => response.json())
  .then(data => {
    console.log(data);
  })
  .catch(error => console.error('Error:', error));

๐Ÿ” While XMLHttpRequest has been the traditional choice, the Fetch API offers a cleaner, promise-based syntax, making code easier to write and maintain.

๐Ÿ†• Developers should prefer Fetch for new projects, but XMLHttpRequest remains relevant for legacy browser support.