How do you create a new XMLHttpRequest object in JavaScript?

The XMLHttpRequest (XHR) object is a key component in making asynchronous requests to web servers using JavaScript.

In this article, we will explain how to create a new XMLHttpRequest object in JavaScript and use it to send and receive data from a web server.

What is an XMLHttpRequest Object?

The XMLHttpRequest (XHR) object is a built-in JavaScript object that enables developers to make HTTP requests to a server and retrieve data from it asynchronously. With XHR, you can update parts of a web page without having to refresh the entire page. This is commonly referred to as AJAX (Asynchronous JavaScript and XML).

Creating a new XMLHttpRequest Object

To create a new XMLHttpRequest object, you can use the XMLHttpRequest() constructor function.

For example:

let xhr = new XMLHttpRequest();

This creates a new instance of the XMLHttpRequest object and assigns it to the xhr variable. You can now use this object to make HTTP requests to a server.

Making a GET Request with XMLHttpRequest

To make a GET request using the XMLHttpRequest object, you need to call the open() method to set up the request and the send() method to send the request.

For example:

let xhr = new XMLHttpRequest();
xhr.open("GET", "https://jsonplaceholder.typicode.com/posts/1");
xhr.send();

xhr.onload = function () {
  if (xhr.status != 200) {
    // handle error
    return;
  }

  console.log(xhr.response);
};

In this example, we are making a GET request to the JSONPlaceholder API to retrieve a post with ID 1. We call the open() method with two arguments: the HTTP method (GET) and the URL to request. We then call the send() method to send the request.

After the request is sent, we set the onload property of the XMLHttpRequest object to a function that will be called when the request is complete. In this function, we check the status property of the XMLHttpRequest object to ensure that the request was successful (status code 200). If there was an error, we can handle it in the if statement. If the request was successful, we log the response to the console.

Making a POST Request with XMLHttpRequest

To make a POST request using the XMLHttpRequest object, you need to call the open() method with the HTTP method POST, set the request headers, and pass the data to send in the send() method.

For example:

let xhr = new XMLHttpRequest();
xhr.open("POST", "https://jsonplaceholder.typicode.com/posts");
xhr.setRequestHeader("Content-Type", "application/json");

let data = JSON.stringify({
  title: "foo",
  body: "bar",
  userId: 1,
});

xhr.send(data);

xhr.onload = function () {
  if (xhr.status != 201) {
    // handle error
    return;
  }

  console.log(xhr.response);
};

In this example, we are making a POST request to the JSONPlaceholder API to create a new post. We call the open() method with the HTTP method POST and the URL to request. We then set the Content-Type header to application/json using the setRequestHeader() method.

We create an object with the data to send and convert it to a JSON string using the JSON.stringify() method. We pass this string to the send() method.

After the request is sent, we set the onload property of the XMLHttpRequest object to a function that will be called when the request is complete. In this function, we check the status property of the XMLHttpRequest object to ensure that the request was successful (status code 201, indicating a new resource was created). If there was an error, we can handle it in the if statement. If the request was successful, we log the response to the console.

Handling Errors with XMLHttpRequest

When making HTTP requests with the XMLHttpRequest object, it is important to handle errors. There are several properties of the XMLHttpRequest object that you can use to check for errors, such as status, statusText, and responseText.

For example:

let xhr = new XMLHttpRequest();
xhr.open("GET", "https://jsonplaceholder.typicode.com/invalid-url");
xhr.send();

xhr.onload = function () {
  if (xhr.status != 200) {
    console.log("Request failed: " + xhr.status + " " + xhr.statusText);
    return;
  }

  console.log(xhr.response);
};

xhr.onerror = function () {
  console.log("Network error");
};

In this example, we are making a GET request to an invalid URL. When the request fails, the onerror property of the XMLHttpRequest object is set to a function that will be called. In this function, we simply log a message to the console indicating that there was a network error.

If the request is successful, the onload property of the XMLHttpRequest object is set to a function that will be called. In this function, we check the status property of the XMLHttpRequest object to ensure that the request was successful. If there was an error, we log a message to the console indicating the status code and status text.

Thank you for reading, and let’s have conversation with each other

Thank you for reading my article. Let’s have conversation on Twitter and LinkedIn by connecting.

Read more: