Clean β’ Professional
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.
const xhttp = new XMLHttpRequest();
Use open() to initialize the request and send() to send it:
xhttp.open("GET", "ajax_info.txt");
xhttp.send();
GET or POST can be used.true or false), username, and password.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();
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 */ }
onreadystatechangeonreadystatechange triggers every time readyState changes.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();
}
| 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 |
| 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 |
Advantages:
Limitations:
fetch("ajax_info.txt")
.then(res => res.text())
.then(data => console.log(data))
.catch(err => console.error(err));Β