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 requestsend(data)β Sends the request (with optional data)onreadystatechangeβ Event that tracks state changesreadyStateβ 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
GETrequest tousers.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
| Value | State | Description |
|---|---|---|
| 0 | UNSENT | Request created but not opened |
| 1 | OPENED | open() method has been called |
| 2 | HEADERS_RECEIVED | send() method has been called |
| 3 | LOADING | Downloading response |
| 4 | DONE | Operation complete β now handle it |
Tips for Efficient Usage
- Always check
readyState === 4 && status === 200before processing - Set request headers only after
open()but beforesend() - Avoid synchronous requests (
async = false) β they block the UI - Use
JSON.stringify()to send JSON data - Use
JSON.parse()to read JSON responses (or setresponseType = "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()andsend()to make HTTP requests - Use
onreadystatechangeto 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
responseTypefor 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 :
