Making Requests with JavaScript XMLHttpRequest Object

To make a request using a JavaScript XMLHttpRequest object, you must first create an XMLHttpRequest object and then open the target URL by calling the xhr.open() method. POST data can be sent to the server by passing it to the xhr.send() method. Custom HTTP headers can be added to the request using the xhr.setRequestHeader(). The xhr.onload event will be fired after the XMLHttpRequest object has completed the asynchronous request. An xhr.status value of 200x indicates that the request was successful, 300x indicates a redirect, and 400x and 500x indicate an error. In this JavaScript XMLHttpRequest Request example, we make a request to the ReqBin echo URL. Click Execute to run JavaScript XMLHttpRequest example online and see the result.
Making Requests with JavaScript XMLHttpRequest Object Execute
let xhr = new XMLHttpRequest();

xhr.open("POST", "https://reqbin.com/echo/post/json");

let data = {
  "Id": 78912,
  "Customer": "Jason Sweet",
};

xhr.onload = () => console.log(xhr.status);

xhr.send(data);

Updated: Viewed: 9790 times

What is JavaScript?

JavaScript is a scripting language that works both on the client-side (in browsers) and on the server-side (Node.js). JavaScript code is called a script. JavaScript scripts can manipulate the content of a web page, interact with the user, process mouse clicks, and post requests to the server using the XMLHttpRequest object or the Fetch API.

What is XMLHttpRequest?

XMLHttpRequest is a built-in browser object that is used to communicate with the server in pure JavaScript. With the XMLHttpRequest object, you can receive data from the server or send data to the server using the XMLHttpRequest object without reloading the entire web page. XMLHttpRequest is mainly used in AJAX programming. Today there is a more modern way to send requests to the server: Fetch API. XMLHttpRequest is used mainly for historical reasons, as there is a lot of legacy code based on XMLHttpRequest, as well as the need to support older browsers.

When to choose XMLHttpRequest over Fetch API?
  • Need to support older browsers but avoid using polyfills.
  • For historical reasons, there is a lot of code that uses XMLHttpRequest that needs to be supported
  • The Fetch API cannot yet provide tracking of the progress of sending to the server

How to use XMLHttpRequest?

XMLHttpRequest has two modes of operation: asynchronous and synchronous. In most cases, asynchronous requests are used. To make a request, we need to follow these steps:

1. Create an XMLHttpRequest object

let xhr = new XMLHttpRequest()

2. Initialize the created object using the xhr.open() method:

xhr.open(method, URL, [async, user, password])

Where:
  • method: HTTP method
  • URL: the URI where the request is sent (string or a URL object)
  • async (optional): if set to false, then the request will be executed synchronously (default true)
  • user, password (optional): login and password for basic HTTP authorization

3. Submit an request usin the xhr.send() method:

xhr.send([body])

The optional body parameter contains POST, PUT, and PATCH requests data. Some request types, such as GET, HEAD do not have a body.

You need to listen to events on the xhr object in order to be notified when the status of a request changes. The most used events are:

  • xhr.onload: occurs when any response is received from the server, including HTTP error responses
  • xhr.onprogress: occurs periodically during a response (useful for showing the progress of the request)
  • xhr.onreadystatechange: notifies when the status of an XMLHttpRequest has changed (e.g. the request has completed)
  • xhr.onerror: indicates that the request could not be completed, for example, a connection could not be established or an invalid URL was specified

4. If you need to cancel the request, you can use the xhr.abort() method. This method generates an abort event and sets xhr.status to 0.

xhr.abort()

JavaScript XMLHttpRequest Request Examples

An example of sending a GET request to the ReqBin echo URL.

XMLHttpRequest GET Request Example
let xhr = new XMLHttpRequest();

xhr.open("GET", "https://reqbin.com/echo/get/json");

xhr.onload = () => {
  if (xhr.status != 200) { 
    console.log(`Error ${xhr.status}: ${xhr.statusText}`);
  } else {
    console.log(xhr.response.length);
  }
};

xhr.onreadystatechange = () => {
  if (xhr.readyState === 4) {
    console.log(xhr.responseText);
  }
};

xhr.onerror = () => console.log("Request failed");

xhr.send();

JavaScript XMLHttpRequest Asynchronous Request Example

XMLHttpRequest always sends an asynchronous request unless otherwise specified. Below is an example of an async request to the ReqBin echo URL with XMLHttpRequest object:

XMLHttpRequest Async Request Example
let xhr = new XMLHttpRequest();

xhr.open("GET", "https://reqbin.com/echo/get/json");

xhr.onreadystatechange = () => {
  if (xhr.readyState === 4) {
    console.log(xhr.responseText);
  }
};

xhr.send();

JavaScript XMLHttpRequest Synchronous Request Example

If the third parameter async is set to false in the xhr.open() method, the request is executed synchronously. In other words, JavaScript execution stops at xhr.send() and resumes when the response is received. Synchronous requests can be useful for debugging your code. It is not recommended to use synchronous requests on your production site as it can negatively impact your app's performance and user experience.

XMLHttpRequest Sync Request Example
let xhr = new XMLHttpRequest();

xhr.open("GET", "https://reqbin.com/echo/get/json", false);

try {
  xhr.send();
  if (xhr.status != 200) {
    console.log(`Error ${xhr.status}: ${xhr.statusText}`);
  } else {
    console.log(xhr.response);
  }
} catch(err) {
  console.log("Request failed");
}

Synchronous XMLHttpRequest requests are rarely used because they block JavaScript execution until the request is complete. If the synchronous request takes too long for some reason, the browser will offer to close the “hung” page. Many advanced features of XMLHttpRequest, such as making a request to a different domain or setting a timeout, are not available for synchronous requests.

How to post JSON data using XMLHttpRequest?

To post data using a JavaScript XMLHttpRequest object, you need to pass an HTTP POST method when calling the xhr.open("POST", URL) method. To post data in JSON format using XMLHttpRequest, you need to convert the JavaScript object to a string using the JSON.stringify() method and provide a "Content-Type: application/json" header along with your request. Below is an example of sending JSON data to the ReqBin echo URL:

XMLHttpRequest Send JSON Data Example
let xhr = new XMLHttpRequest();

xhr.open("POST", "https://reqbin.com/echo/post/json");

xhr.setRequestHeader("Content-Type", "application/json");

let data = `{
  "Id": 78912,
  "Customer": "Jason Sweet",
}`;

xhr.onload = () => console.log(xhr.responseText);

xhr.send(data);

How to post HTML Form data using XMLHttpRequest?

To post HTML data with a JavaScript XMLHttpRequest object, you need to set "Content-Type" to "application/x-www-form-urlencoded" and pass the form data as key=value pairs to the xhr.send() method. Below is an example of sending HTML Form data to the ReqBin echo URL.

XMLHttpRequest post HTML Form Data Example
let xhr = new XMLHttpRequest();

xhr.open("POST", "https://reqbin.com/echo/post/form");

xhr.setRequestHeader("Content-Type", "application/x-www-form-urlencoded");

let data = "key1=value1&key2=value2";

xhr.onload = () => console.log(xhr.responseText);

xhr.send(data);

How to post XML data using XMLHttpRequest?

To send data in XML format using a JavaScript XMLHttpRequest object, you need to set "Content-Type" to "application/xml" and pass XML string to the xhr.send() method. Below is an example of sending XML data to the ReqBin echo URL.

XMLHttpRequest post XML Data Example
let xhr = new XMLHttpRequest();

xhr.open("POST", "https://reqbin.com/echo/post/xml");

xhr.setRequestHeader("Content-Type", "application/xml");

let data = `<?xml version="1.0" encoding="utf-8"?>
<Request>
    <Login>login</Login>
    <Password>password</Password>
</Request>`;

xhr.onload = () => console.log(xhr.responseText);

xhr.send(data);

How to set a timeout on XMLHttpRequest?

You can use the xhr.timeout property to set a timeout for an XMLHttpRequest. The timeout is specified in milliseconds. The default value is 0, which means the request has no timeout.

XMLHttpRequest Timeout Example
let xhr = new XMLHttpRequest();

xhr.open("GET", "https://reqbin.com/echo/get/json");

xhr.timeout = 10000;

xhr.onload = function () {
  console.log('Request finished')
};

xhr.ontimeout = function () {
  console.log('XMLHttpRequest timed out')
};

xhr.send();

See also