Using XMLHttpRequest – JavaScript (a.k.a. The Ancient Art of Fetching Data)

 

Before the Fetch API made our lives easier, JavaScript developers had to use XMLHttpRequest (XHR)—a name so long it already feels outdated. But hey, sometimes you need to work with legacy systems, or just want to experience the "good old days" (read: unnecessary complexity). In this guide, we’ll explore XMLHttpRequest in a way that’s fun, optimized for SEO, and doesn’t make you fall asleep. Let’s dive in!

What is XMLHttpRequest?

XMLHttpRequest (XHR) is JavaScript’s old-school way of making HTTP requests. It allows you to:

  • Fetch data from a server (GET request)
  • Send data to a server (POST request)
  • Handle JSON responses (though not as smoothly as Fetch API)
  • Feel nostalgic about early web development

Basic Syntax: How to Make a GET Request

Before Fetch API, this was how developers retrieved data:

let xhr = new XMLHttpRequest();
xhr.open("GET", "https://api.example.com/data", true);

xhr.onload = function () {
  if (xhr.status >= 200 && xhr.status < 300) {
    console.log(JSON.parse(xhr.responseText));
  } else {
    console.error("Error: ", xhr.status);
  }
};

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

xhr.send();

Explanation:

  1. new XMLHttpRequest(): Creates a new request object.
  2. xhr.open("GET", url, true): Initializes a GET request (true means it’s asynchronous).
  3. xhr.onload: Handles the response when the request is successful.
  4. xhr.onerror: Handles network errors.
  5. xhr.send(): Sends the request.

Making a POST Request (a.k.a. Sending Data Like a Boss)

Want to send data to a server? Here’s how:

let xhr = new XMLHttpRequest();
xhr.open("POST", "https://api.example.com/data", true);
xhr.setRequestHeader("Content-Type", "application/json");

xhr.onload = function () {
  if (xhr.status >= 200 && xhr.status < 300) {
    console.log("Success!", JSON.parse(xhr.responseText));
  } else {
    console.error("Error: ", xhr.status);
  }
};

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

let data = JSON.stringify({ username: "CodeNinja", score: 9000 });
xhr.send(data);

Important Parts of a POST Request:

  • xhr.open("POST", url, true): Specifies the request method.
  • xhr.setRequestHeader("Content-Type", "application/json"): Tells the server we’re sending JSON.
  • xhr.send(data): Sends the request with JSON data.

Handling Errors (Because Things Break!)

Things don’t always go smoothly, so error handling is crucial:

xhr.onerror = function () {
  console.error("Oops! Something went wrong.");
};

Also, check for HTTP status codes inside xhr.onload:

if (xhr.status >= 200 && xhr.status < 300) {
  console.log("Success!");
} else {
  console.error("Error: ", xhr.status);
}

Why Use XMLHttpRequest in 2025?

  • Legacy Systems: Some old APIs still rely on XHR.
  • Internet Explorer Support: (Wait, people still use IE?)
  • Synchronous Requests: Unlike Fetch, XHR supports blocking requests (not recommended, though).

Why You Probably Shouldn't Use XMLHttpRequest

  • It’s Verbose: Fetch API is cleaner and easier to use.
  • No Promises: XHR relies on callbacks, making it less elegant than Fetch with async/await.
  • Error Handling is Clunky: With Fetch, checking response.ok is enough.

Conclusion

If XMLHttpRequest were a person:

  • Fetch API: The young, efficient, and modern developer.
  • XMLHttpRequest: The old-school coder who refuses to upgrade from Windows XP.

That said, knowing XHR can still be useful, especially when dealing with legacy systems. But for new projects? Stick to Fetch API! Happy coding! 

Post a Comment

0 Comments