β‘ AJAX β Creating XMLHttpRequest Object (Step-by-Step Guide with Examples)
π§² Introduction β What Is XMLHttpRequest in AJAX?
AJAX (Asynchronous JavaScript and XML) allows web pages to update data asynchronously without refreshing the page. The core of AJAX is the XMLHttpRequest object, which enables data exchange between a client and a server.
This guide will walk you through how to create, configure, and use the XMLHttpRequest object to send and receive data with modern AJAX applications.
π§± What Is XMLHttpRequest?
The XMLHttpRequest object is used to interact with servers via JavaScript. It enables:
- Sending and receiving data in background
- Updating parts of a webpage without full reload
- Handling responses in formats like JSON, XML, HTML, or plain text
π οΈ How to Create XMLHttpRequest Object
β Basic Syntax (Modern Browsers):
let xhr = new XMLHttpRequest();
This creates an instance of the XMLHttpRequest class in all modern browsers (Chrome, Firefox, Safari, Edge).
π§° Compatibility with Older IE Versions (IE5, IE6):
let xhr;
if (window.XMLHttpRequest) {
// Modern browsers
xhr = new XMLHttpRequest();
} else {
// Internet Explorer 5/6
xhr = new ActiveXObject("Microsoft.XMLHTTP");
}
π‘ Note: ActiveXObject is no longer used in modern development.
π€ Sending a Request to the Server
Once the object is created, you can open and send a request.
π‘ GET Request Example:
let xhr = new XMLHttpRequest();
xhr.open("GET", "data.json", true); // method, URL, async
xhr.send();
π© POST Request Example:
let xhr = new XMLHttpRequest();
xhr.open("POST", "submit.php", true);
xhr.setRequestHeader("Content-Type", "application/x-www-form-urlencoded");
xhr.send("name=John&age=30");
π Handling Server Response
After sending the request, monitor its state using onreadystatechange:
xhr.onreadystatechange = function() {
if (xhr.readyState === 4 && xhr.status === 200) {
// Success
console.log(xhr.responseText);
}
};
π§ readyState Values:
| State | Description |
|---|---|
| 0 | Request not initialized |
| 1 | Server connection established |
| 2 | Request received |
| 3 | Processing request |
| 4 | Request finished and response is ready |
π§ status Values:
| Status Code | Meaning |
|---|---|
| 200 | OK (Success) |
| 404 | Not Found |
| 500 | Server Error |
π§ͺ Full Working Example
π HTML (index.html)
<button onclick="loadData()">Get Data</button>
<div id="output"></div>
βοΈ JavaScript
function loadData() {
const xhr = new XMLHttpRequest();
xhr.open("GET", "data.txt", true);
xhr.onreadystatechange = function () {
if (xhr.readyState === 4 && xhr.status === 200) {
document.getElementById("output").innerHTML = xhr.responseText;
}
};
xhr.send();
}
π§ͺ Result: Clicking the button fetches content from
data.txtand displays it inside the#outputdiv.
β
Best Practices for Using XMLHttpRequest
- β
Use
XMLHttpRequestonly when you can’t usefetch()(modern alternative) - β Always check for readyState and status before handling responses
- β Handle error states like 404 or 500 gracefully
- β
Avoid blocking requests (
async = false) β always use asynchronous mode - β
Consider setting request timeouts with
xhr.timeout
π Summary
The XMLHttpRequest object is a foundational part of AJAX development. It allows web pages to communicate with servers asynchronously and dynamically update content. While modern apps favor fetch(), understanding XMLHttpRequest helps when working with legacy systems or needing advanced control
π Key Takeaways:
XMLHttpRequestis the core of traditional AJAX- Use
open()andsend()to initiate requests - Monitor
readyStateandstatusfor response handling - Combine with HTML/CSS to build interactive, data-driven interfaces
- Prefer
fetch()for new projects, but knowXMLHttpRequestfor compatibility
β Frequently Asked Questions (FAQ)
β What is XMLHttpRequest used for?
β Itβs used to send HTTP requests to servers and load data without refreshing the page.
β Whatβs the difference between XMLHttpRequest and fetch()?
β
fetch() is a newer, Promise-based alternative to XMLHttpRequest, offering cleaner syntax.
β Can I send POST data with XMLHttpRequest?
β
Yes. Set the request method to POST and use xhr.send("key=value").
β Does XMLHttpRequest work with JSON?
β
Yes. You can send and receive JSON by setting headers and parsing xhr.responseText with JSON.parse().
β Is XMLHttpRequest still used in 2025?
β
While fetch() is preferred, XMLHttpRequest is still supported in all browsers and widely used in legacy systems.
.
Share Now :