π§ 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
GET
request 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 === 200
before 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
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 :