How do I send XMLHttpRequest with JavaScript?

To send an XMLHttpRequest with JavaScript, you need to create an XMLHttpRequest object, open the URL, and send the request. After the request has been made, the response body can be retrieved and processed using the xhr.response attribute of the XMLHttpRequest object. Additional HTTP headers can be passed to the server using the xhr.setRequestHeader() method. In this JavaScript XMLHttpRequest Request Example, we use the XMLHttpRequest object to send an asynchronous request to the ReqBin echo URL. Click Execute to run JavaScript XMLHttpRequest Example online and see the result.
How do I send XMLHttpRequest with JavaScript? Execute
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);

Updated: Viewed: 1572 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 programs are called scripts. They can be embedded in HTML and CSS and run automatically when the web page loads. JavaScript is considered a "safe" programming language. Browsers implement many technologies to protect users from malicious JavaScript code and prevent it from accessing protected resources. In a browser, JavaScript code can manipulate the content of an HTML web page, interact with the user, process mouse clicks, and send requests to the server.

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 Fetch API method for sending requests to the server. 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 Examples

An example of sending an HTTP 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.onprogress = (event) => console.log(event.loaded);

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 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 XMLHttpRequest, you need to pass a 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 an XMLHttpRequest, 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 XMLHttpRequest, 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?

The xhr.timeout property represents the number of milliseconds a request can take before being aborted. The default value is 0, which means the request does not have a 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