XMLHttpRequest (XHR)
The XMLHttpRequest (XHR) object is a built-in browser API that allows JavaScript to communicate with a server asynchronously, forming the foundation of traditional AJAX. XHR enables partial page updates without reloading the entire page.
Supported in all modern browsers: Chrome, Firefox, Edge, Safari, IE, and Opera.
Creating an XMLHttpRequest Object
const xhttp = new XMLHttpRequest();
- This creates a new XHR object.
- Modern browsers have it built-in; no extra library required.
Sending a Request
Use open()
to initialize the request and send()
to send it:
xhttp.open("GET", "ajax_info.txt");
xhttp.send();
GET
orPOST
can be used.- Optional parameters: async (
true
orfalse
), username, and password.
Callback Functions
Using onload
onload
executes when the request completes successfully:
xhttp.onload = function() {
document.getElementById("demo").innerHTML = this.responseText;
};
xhttp.open("GET", "ajax_info.txt");
xhttp.send();
Multiple Callback Functions for Different Tasks
Allows reusing one XHR function with different callback functions.
loadDoc("url-1", myFunction1);
loadDoc("url-2", myFunction2);
function loadDoc(url, cFunction) {
const xhttp = new XMLHttpRequest();
xhttp.onload = function() { cFunction(this); }
xhttp.open("GET", url);
xhttp.send();
}
function myFunction1(xhttp) { /* action */ }
function myFunction2(xhttp) { /* action */ }
Using onreadystatechange
onreadystatechange
triggers every timereadyState
changes.- The response is ready when readyState = 4 and status = 200.
function loadDoc() {
const xhttp = new XMLHttpRequest();
xhttp.onreadystatechange = function() {
if(this.readyState == 4 && this.status == 200) {
document.getElementById("demo").innerHTML = this.responseText;
}
};
xhttp.open("GET", "ajax_info.txt");
xhttp.send();
}
XHR Object Properties
Property | Description |
---|---|
onload | Function executed when the request completes successfully |
onreadystatechange | Function executed when readyState changes |
readyState | Status of the request (0–4) |
responseText | Response as a string (text, JSON, HTML) |
responseXML | Response as an XML document |
status | HTTP status code (e.g., 200, 403, 404) |
statusText | Status message (e.g., "OK", "Forbidden", "Not Found") |
readyState values:
Value | State | Description |
---|---|---|
0 | UNSENT | Request not initialized |
1 | OPENED | Connection established |
2 | HEADERS_RECEIVED | Request received |
3 | LOADING | Processing request |
4 | DONE | Request finished; response ready |
XHR Object Methods
Method | Description |
---|---|
open(method, url, async, user, psw) | Initializes the request |
send() | Sends the request; optionally send string for POST |
setRequestHeader(header, value) | Sets HTTP headers |
abort() | Cancels the current request |
getResponseHeader(header) | Returns value of a specific header |
getAllResponseHeaders() | Returns all response headers |
Access Across Domains
- For security reasons, browsers block AJAX requests across domains without CORS.
- Both the page and requested file must be on the same server, unless the server allows cross-origin requests.
Advantages & Limitations
Advantages:
- Works in all browsers, modern and older.
- Supports partial page updates.
- Handles multiple data formats (JSON, XML, text, HTML).
Limitations:
- Verbose and complex syntax compared to Fetch API.
- Requires manual handling of JSON/XML parsing.
- Error handling is less intuitive.
Modern Alternative: Fetch API
fetch("ajax_info.txt")
.then(res => res.text())
.then(data => console.log(data))
.catch(err => console.error(err));