DEV Community

Cover image for Understanding AJAX, XMLHttpRequest, and Fetch API in JavaScript
Krushna Sananse
Krushna Sananse

Posted on

Understanding AJAX, XMLHttpRequest, and Fetch API in JavaScript

When it comes to making requests to a server from a webpage without reloading it, JavaScript provides several powerful tools. In this blog post, we'll explore the key players in this domain: AJAX, XMLHttpRequest, and the modern Fetch API.

What is AJAX?

AJAX stands for Asynchronous JavaScript and XML. It allows you to:

  • Fetch data from a server in the background.
  • Update parts of a webpage without a full reload.
  • Improve the user experience by creating dynamic, fast-loading web application

AJAX isn’t a single technology but a group of technologies working together. It typically involves:

  • HTML/CSS for structure and styling.
  • JavaScript for logic.
  • XML or JSON for data exchange.
  • Server-side languages like PHP, Node.js, or Python.

XMLHttpRequest (XHR)

Introduced in the early days of AJAX, XMLHttpRequest is a built-in JavaScript object that lets you interact with servers.

Example of XMLHttpRequest:

const xhr = new XMLHttpRequest();

// Configure the request
xhr.open('GET', 'https://jsonplaceholder.typicode.com/posts', true);

// Add event listener for the response
xhr.onload = function () {
  if (xhr.onreadystate == 4 && xhr.status === 200) {
    console.log(JSON.parse(xhr.responseText));
  } else {
    console.error('Error fetching data:', xhr.status);
  }
};

// Send the request
xhr.send();
Enter fullscreen mode Exit fullscreen mode

Key Features of XMLHttpRequest:

  • Supports GET, POST, and other HTTP methods.
  • Handles response types like text, JSON, or XML.
  • Relies on event listeners for asynchronous operations.

While XHR is still widely used, its syntax can be verbose and less intuitive compared to modern alternatives.

Fetch API

The Fetch API is a modern alternative to XMLHttpRequest, introduced in ES6. It’s simpler, more powerful, and uses Promises to handle asynchronous operations.

Example of Fetch API:

fetch('https://jsonplaceholder.typicode.com/posts')
  .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('Fetch error:', error));
Enter fullscreen mode Exit fullscreen mode

Why Use Fetch?

  • Cleaner Syntax: It’s easier to read and write compared to XHR.
  • Promises: Makes it easier to handle asynchronous tasks.
  • Supports Streaming: Fetch streams responses, which can improve performance.

Key Differences Between XHR and Fetch

Here are the main differences between XMLHttpRequest and Fetch API:

  • Syntax: XHR uses a verbose callback-based syntax, while Fetch has a cleaner and more modern Promise-based syntax.
  • Promises: XHR does not natively support Promises, whereas Fetch supports Promises out of the box, making it easier to handle asynchronous operations.
  • Streaming: Fetch supports response streaming, allowing for more efficient data handling, which is not possible with XHR.
  • Error Handling: XHR relies on callback-based error handling, while Fetch makes use of Promise chaining and catch for better error management.

Which One Should You Use?

  • Use Fetch for new projects because it’s modern, concise, and aligns with JavaScript’s future.
  • Use XHR for legacy systems or if you’re maintaining older projects.

Pro Tip:

Always use async/await with Fetch to make your code cleaner and more readable:

async function fetchData() {
  try {
    const response = await fetch('https://jsonplaceholder.typicode.com/posts');
    if (!response.ok) {
      throw new Error('Network response was not ok');
    }
    const data = await response.json();
    console.log(data);
  } catch (error) {
    console.error('Fetch error:', error);
  }
}
fetchData();
Enter fullscreen mode Exit fullscreen mode

Learn More:

I’ve also created a video explaining the differences between AJAX, XHR, and Fetch API on my Instagram account. Check it out here: Instagram Video on AJAX and Fetch

Let’s Collaborate!

Are you a fellow blogger or a learner exploring JavaScript? Let’s connect and collaborate! Share your thoughts, experiences, or code snippets in the comments below. Together, we can create a vibrant community of developers helping each other grow. Feel free to reach out—I’d love to hear your story and explore new ideas with you!

JavaScript #Coding #AJAX #FetchAPI #WebDevelopment #FrontendDevelopment #WebDev #LearnCoding #TechExplained #AsyncJavaScript

Top comments (0)