JavaScript XMLHTTPRequest Example: Fetch Data Easily

Sarah Jul 13, 2026

JavaScript's XMLHTTPRequest (XHR) is a vital tool for client-side Developers, enabling asynchronous data transfer between a web browser and a server. It's widely used in web development for creating dynamic single page applications (SPAs), mobile apps, and real-time updates. Here, we'll explore XMLHTTPRequest, its key features, and examine its usage with a practical example.

Get Gravatar Image Using Ajax XMLHttpRequest Example
Get Gravatar Image Using Ajax XMLHttpRequest Example

Before diving into XHR, let's quickly understand its role in JavaScript. JavaScript is single-threaded, meaning it executes one statement at a time. XHR fulfills an essential need in web development: performing actions in the background, without halting the main thread's execution, thus enhancing the user experience.

Javascript Fundamental
Javascript Fundamental

Setting Up and Sending a Request

To initialize an XHR, we first create an instance of the XMLHttpRequest object.

JavaScript Cheatsheet for Beginners | Learn JS Fast (One-Page Guide)
JavaScript Cheatsheet for Beginners | Learn JS Fast (One-Page Guide)

Here's how you'd initiate a new XHR in JavaScript:

let xhr = new XMLHttpRequest();

Async vs Sync Requests

Writing Conditional Statements in JavaScript
Writing Conditional Statements in JavaScript

XHR supports both asynchronous (async) and synchronous (sync) requests. Async requests allow JavaScript to continue executing while the request is in progress, while sync requests halt execution until the requestๅฎŒๆˆ.

For most applications, you'll want to use async requests to keep your user interface responsive. Here's how to set up an async request:

xhr.open('GET', 'https://api.example.com/data', true);

Onreadystatechange Event

JavaScript Basics | Chapter 1 ๐Ÿ“– | Part 1
JavaScript Basics | Chapter 1 ๐Ÿ“– | Part 1

The readyState property of an XHR object indicates the current status of a request. When it changes, the `onreadystatechange` event is triggered. We typically associate a handler function with this event to respond to changes in readyState.

Here's an example of doing so:

xhr.onreadystatechange = function() {
  if (this.readyState == 4 && this.status == 200) {
    console.log(this.responseText);
  }
};

Sending Data to the Server

โณ Master JavaScript setTimeout(): Delay Code Execution Like a Pro! ๐Ÿ’ปโœจ  Pin Description:
โณ Master JavaScript setTimeout(): Delay Code Execution Like a Pro! ๐Ÿ’ปโœจ Pin Description:

XHR isn't limited to sending requests; it can also send data to a server. This is achieved by setting the `send()` method's parameter to the data you want to send.

Here's an example of sending data using an `object` parameter:

JavaScript Full Notes Every Beginner Must Save ๐Ÿ’ก
JavaScript Full Notes Every Beginner Must Save ๐Ÿ’ก
JavaScript Return Values: Get the Most Out of Your Functions ๐Ÿš€
JavaScript Return Values: Get the Most Out of Your Functions ๐Ÿš€
Javascript Cheet cheet
Javascript Cheet cheet
JavaScript Basics You MUST Know
JavaScript Basics You MUST Know
How to Create a Function in JavaScript: Step-by-Step Guide ๐Ÿš€
How to Create a Function in JavaScript: Step-by-Step Guide ๐Ÿš€
Java script string method
Java script string method
JavaScript study guide for fast learning
JavaScript study guide for fast learning
JavaScript Works in the Browser
JavaScript Works in the Browser
JavaScript Basics | Chapter 1 ๐Ÿ“– | Part 2
JavaScript Basics | Chapter 1 ๐Ÿ“– | Part 2
Synchronous & Asynchronous Javascript
Synchronous & Asynchronous Javascript
Javascript Loops & Iterations
Javascript Loops & Iterations
JavaScript if Statement: Control Program Flow Like a Pro โœ…
JavaScript if Statement: Control Program Flow Like a Pro โœ…
JavaScript Template Literals: Write Cleaner & Dynamic Strings ๐Ÿ“
JavaScript Template Literals: Write Cleaner & Dynamic Strings ๐Ÿ“
Javascript window.confirm() method | Javascript tutorial
Javascript window.confirm() method | Javascript tutorial
JavaScript Form Events: Handle User Input Like a Pro ๐Ÿ“
JavaScript Form Events: Handle User Input Like a Pro ๐Ÿ“
JavaScript while Loop: Repeat Tasks Efficiently ๐Ÿ”„
JavaScript while Loop: Repeat Tasks Efficiently ๐Ÿ”„
an info sheet with different types of web pages
an info sheet with different types of web pages
an image of a web page with different types of text
an image of a web page with different types of text
JavaScript loops by Duomly
JavaScript loops by Duomly

First, let's prepare an object containing the data:

let data = { 'param1': 'value1', 'param2': 'value2' };

Next, send the data using the `send()` method:

xhr.send(JSON.stringify(data));

Using the FormData Interface

For sending large amounts of data, the `FormData` interface is particularly useful. This interface represents a set of form keys and values that you can send in a single request.

Here's an example of setting up a `FormData` object and attaching it to the XHR's send method:

let formData = new FormData();
formData.append('param1', 'value1');
formData.append('param2', 'value2');
xhr.send(formData);

Error Handling in XHR

A critical aspect of using XHR is handling potential errors. Servers can respond with error codes, and networks can drop connections. Let's configure the XHR to throw an event when an error occurs:

To do this, we will add an `error` event listener:

xhr.onerror = function() { console.log('Error occurred:', this.error); };

This will log an error message to the console whenever a network error occurs.

JavaScript's XHR is a robust tool, but it's not the only way to send requests. With the advent of Promise-based and Async/Await APIs like fetch(), JavaScript developers now have more options to choose from when dealing with HTTP requests.

However, understanding the basics of XMLHTTPRequest will always be beneficial, as it forms the backbone of the more modern APIs. It's a fundamental part of JavaScript's evolution, and mastering it can give you a strong foundation in making client-side data requests.