βοΈ AJAX β XMLHttpRequest Object: A Complete Guide for Beginners
π§² Introduction β Why Learn XMLHttpRequest in AJAX?
The XMLHttpRequest object is the backbone of traditional AJAX programming. Long before the fetch() API gained popularity, XMLHttpRequest allowed web pages to communicate with the server in the background, enabling partial updates without page reloads.
Even today, it remains essential for understanding how asynchronous communication works at a lower level.
π― In this article, you’ll learn:
- What XMLHttpRequest is and how it works
- Syntax and readyState lifecycle
- Full examples of GET and POST requests
- How to handle responses, errors, and status codes
π What Is XMLHttpRequest in AJAX? (Primary Keyword)
The XMLHttpRequest (XHR) object is a built-in JavaScript object used to exchange data with a web server without reloading the page.
It supports both synchronous and asynchronous modes and can handle:
- Text
- HTML
- XML
- JSON
π§± Basic Syntax and Lifecycle
var xhr = new XMLHttpRequest();
xhr.open("GET", "data.txt", true); // true = asynchronous
xhr.send();
π Lifecycle (readyState values):
| Value | Meaning |
|---|---|
| 0 | Request not initialized |
| 1 | Server connection established |
| 2 | Request received |
| 3 | Processing request |
| 4 | Request finished and response is ready β |
π₯ AJAX GET Request with XMLHttpRequest
var xhr = new XMLHttpRequest();
xhr.open("GET", "data.json", true);
xhr.onreadystatechange = function() {
if (xhr.readyState === 4 && xhr.status === 200) {
const data = JSON.parse(xhr.responseText);
console.log("User:", data.user);
}
};
xhr.send();
β
This sends a GET request to data.json and logs the user data once the response is complete.
π AJAX POST Request with XMLHttpRequest
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("response").innerHTML = xhr.responseText;
}
};
xhr.send("name=John&email=john@example.com");
β
This sends form data to submit.php and updates the DOM with the server’s response.
π¨ Handling Errors in XMLHttpRequest
xhr.onerror = function () {
console.error("Request failed.");
};
xhr.ontimeout = function () {
console.error("Request timed out.");
};
xhr.timeout = 5000; // Set timeout to 5 seconds
β Use these events to handle failures and set timeouts for slow requests.
π XMLHttpRequest vs fetch()
| Feature | XMLHttpRequest | fetch() |
|---|---|---|
| Syntax | Verbose | Cleaner (Promise-based) |
| Browser Support | Widely supported | Modern browsers only |
| Error Handling | Manual event handling | .catch() or try/catch |
| Stream Handling | Basic | Advanced (ReadableStream) |
π§ Best Practices for Using XMLHttpRequest
- β
Always check
readyState === 4 && status === 200before processing - β
Use
setRequestHeader()when sending POST data - β Prefer asynchronous requests for non-blocking performance
- β
Use
try/catcharound JSON parsing - β
Consider replacing with
fetch()for newer apps
π Summary β Recap & Takeaways
The XMLHttpRequest object was the original driver of AJAX. Though newer APIs like fetch() exist, XMLHttpRequest is still a reliable method for sending and receiving HTTP requests asynchronously.
π Key Takeaways:
- XMLHttpRequest enables browser-server communication without page reloads
- It supports both GET and POST methods
- Use
onreadystatechangeto handle responses - Use error events like
onerrorandontimeoutfor reliability
βοΈ Next Steps:
- Practice creating CRUD operations with XMLHttpRequest
- Compare XMLHttpRequest with fetch in real projects
- Explore XML parsing with
responseXML
β FAQs β XMLHttpRequest in AJAX
β What is XMLHttpRequest used for in AJAX?
β
It allows JavaScript to send and receive data asynchronously from the server without reloading the webpage.
β What are the readyState values in XMLHttpRequest?
β
0: uninitialized, 1: opened, 2: headers received, 3: loading, 4: done.
β How to check if an AJAX request is successful?
β
Check xhr.readyState === 4 and xhr.status === 200 in the onreadystatechange function.
β Can XMLHttpRequest send JSON data?
β
Yes. Set Content-Type: application/json and use JSON.stringify(data) in the send() method.
β Is XMLHttpRequest still supported in modern browsers?
β
Yes, but itβs being replaced by fetch() in most new applications due to better syntax and promise support.
Share Now :
