πŸ” AJAX Request & Response Lifecycle
Estimated reading: 4 minutes 389 views

AJAX – XMLHttpRequest Object Usage: How to Send and Handle Asynchronous Requests


Introduction – Why Learn XMLHttpRequest Usage?

Before modern APIs like fetch() became popular, the XMLHttpRequest object was the backbone of AJAX-based web applications. It still remains relevant today, especially for legacy systems or when you need more control over AJAX requests.

Understanding how to use XMLHttpRequest allows developers to:

  • Build AJAX requests manually
  • Control request headers and response types
  • Manage timeouts, errors, and ready states precisely

In this article, you’ll learn:

  • How to create and configure XMLHttpRequest
  • How to send GET and POST requests
  • How to handle responses and errors
  • Practical examples with explanations

What Is the XMLHttpRequest Object?

The XMLHttpRequest object is a built-in JavaScript interface that allows the browser to:

  • Send HTTP requests to the server
  • Receive responses asynchronously
  • Update parts of the webpage without refreshing

It supports HTTP methods like GET, POST, PUT, DELETE, and more.


Basic Syntax of XMLHttpRequest

var xhr = new XMLHttpRequest();
xhr.open("GET", "data.txt", true);  // true = asynchronous
xhr.send();
  • open(method, url, async) – Prepares the request
  • send(data) – Sends the request (with optional data)
  • onreadystatechange – Event that tracks state changes
  • readyState – Current state of the request (0–4)
  • status – HTTP response status (200 = OK)

Example – Sending a GET Request

var xhr = new XMLHttpRequest();
xhr.open("GET", "users.json", true);

xhr.onreadystatechange = function () {
  if (xhr.readyState === 4 && xhr.status === 200) {
    var data = JSON.parse(xhr.responseText);
    console.log("User:", data.name);
  }
};

xhr.send();

This code:

  • Sends a GET request to users.json
  • Waits for a complete response
  • Parses and logs the JSON data

Example – Sending a POST Request

var xhr = new XMLHttpRequest();
xhr.open("POST", "submit.php", true);
xhr.setRequestHeader("Content-Type", "application/x-www-form-urlencoded");

xhr.onreadystatechange = function () {
  if (xhr.readyState === 4 && xhr.status === 200) {
    document.getElementById("result").innerHTML = xhr.responseText;
  }
};

xhr.send("name=John&email=john@example.com");

This code:

  • Sends form data as a POST request
  • Uses setRequestHeader() to specify encoding
  • Updates the page dynamically with the server’s response

Error Handling with XMLHttpRequest

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

xhr.ontimeout = function () {
  console.error("Request timed out.");
};

xhr.timeout = 5000;  // Timeout after 5 seconds

Always include error handlers to manage network issues or server failures.


Working with Different Response Types

JSON Response:

xhr.responseType = "json";
xhr.onload = function () {
  console.log(xhr.response);  // Already parsed JSON
};

Text Response:

xhr.responseType = "text";

XML Response:

xhr.responseType = "document";

Use the correct responseType for smooth data handling.


XMLHttpRequest Lifecycle – readyState Values

ValueStateDescription
0UNSENTRequest created but not opened
1OPENEDopen() method has been called
2HEADERS_RECEIVEDsend() method has been called
3LOADINGDownloading response
4DONEOperation complete – now handle it

Tips for Efficient Usage

  • Always check readyState === 4 && status === 200 before processing
  • Set request headers only after open() but before send()
  • Avoid synchronous requests (async = false) β€” they block the UI
  • Use JSON.stringify() to send JSON data
  • Use JSON.parse() to read JSON responses (or set responseType = "json")

Summary – Recap & Key Points

The XMLHttpRequest object remains a reliable and powerful option for asynchronous client-server communication. Whether you’re building legacy support, working with older systems, or simply learning how AJAX works under the hood, mastering XHR is a valuable skill.

Key Takeaways:

  • Use open() and send() to make HTTP requests
  • Use onreadystatechange to monitor and handle AJAX states
  • Use setRequestHeader() to define headers for POST requests
  • Always handle errors and timeouts to improve UX

Next Steps:

  • Try building a small CRUD app using XMLHttpRequest
  • Compare with the modern fetch() API
  • Explore responseType for advanced data formats

FAQs – XMLHttpRequest Usage


Do I need to use XMLHttpRequest in modern web apps?
It’s still useful for learning and legacy projects, but fetch() is preferred for new apps due to cleaner syntax and promises.


How do I send form data using XMLHttpRequest?
Use setRequestHeader("Content-Type", "application/x-www-form-urlencoded") and pass URL-encoded data via send().


Can I send JSON with XMLHttpRequest?
Yes. Set the content type to application/json and use JSON.stringify():

xhr.setRequestHeader("Content-Type", "application/json");
xhr.send(JSON.stringify({ name: "John" }));

How do I handle server errors?
Check for non-200 status codes in xhr.status, and use onerror to handle network issues.


What is the difference between xhr.responseText and xhr.response?
responseText always returns plain text. response adapts based on responseType (e.g., json, document, blob).


Share Now :
Share

AJAX – XMLHttpRequest Object Usage

Or Copy Link

CONTENTS
Scroll to Top