DEV Community

Bhuvana Sri R
Bhuvana Sri R

Posted on

XMLHttpRequest in JavaScript

What is XMLHttpRequest (XHR)?

  • XMLHttpRequest is a built-in JavaScript object used to send HTTP requests to a server and load data without reloading the whole page.
  • It was introduced in the early 2000s and is the technology behind AJAX (Asynchronous JavaScript and XML).
  • Even though it has “XML” in its name, it can handle JSON, text, XML, or any data.

Why was it important?

  • Before XMLHttpRequest, if you wanted new data from the server, the entire web page had to reload.
  • With XHR, JavaScript could:
  • Request data asynchronously in the background.
  • Update part of the page dynamically.

Example :

Basis Syntax

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

xhr.onload = function () {
  if (xhr.status === 200) {
    console.log(JSON.parse(xhr.responseText));
  } else {
    console.error("Request failed with status", xhr.status);
  }
};

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

xhr.send();

Enter fullscreen mode Exit fullscreen mode

Output Example :

For the above request, you’ll get:

{
  "userId": 1,
  "id": 1,
  "title": "sunt aut facere repellat provident occaecati excepturi         optio reprehenderit",
  "body": "quia et suscipit\nsuscipit recusandae..."
}

Enter fullscreen mode Exit fullscreen mode
  • Works with callbacks (not Promises).
  • More verbose than fetch.
  • Still supported in all browsers for backward compatibility.
  • Mostly replaced by fetch and Axios in modern JavaScript.

XMLHttpRequest still works, but it’s old, clunky, and hard to maintain. That’s why modern code uses fetch or libraries like Axios.

Top comments (0)