What is XMLHttpRequest() in JavaScript?

In JavaScript, the XMLHttpRequest method is used to make asynchronous requests to the server and load the information that is returned by the server onto the web pages.

Thus, it enables us to update parts of a web page without reloading the whole page.

The XMLHttpRequest() method:

  • creates an XMLHttpRequest object.
  • creates a callback function.

With the XMLHttpRequest object, we can send a request to the server using the open() and send() methods respectively, and retrieve data from the server.

Syntax

The following is the syntax to create a new XMLHttpRequest object.

const xhr = new XMLHttpRequest();

Create a callback function

The callback function contains the code to execute after the server returns a response and the response is in the ready state.

When the readyState property is 4 and the status property is 200, the response is ready.

onreadystatechange() specifies that a function will be executed every time the status of the XMLHttpRequest object changes.

xhr.onreadystatechange = function() {
  // function body
}

Send a request to the server

To send a request to a server, we use the open() and send() methods.

xhr.open('GET', 'https://reqres.in/api/products');
xhr.send();

The open() methods basically have two non-optional parameters:

  1. Method type: GET, POST, PUT, or DELETE.
  2. URL: The URL on which the request is to be made.

Code

Let’s make some requests to a public URL and see how XMLHttpRequest works.

Console

Thus, we can make a request to the server and get data without refreshing or reloading the page. We can also make a POST request to the server. An example of this is shown below.

Console

Free Resources