XMLHttpRequest (XHR) is a browser API for sending HTTP requests without reloading the whole page. Modern browsers also provide the fetch() API, which usually gives new code a simpler promise-based interface.
This example calls the GET processor used in the AJAX GET tutorial. The query value is encoded with URLSearchParams, the HTTP status is checked, and the plain-text response is returned.
async function loadMessage(name) {
const params = new URLSearchParams({ txt: name });
const response = await fetch(`ajax-get-testck.php?${params}`);
if (!response.ok) {
throw new Error(`HTTP ${response.status}`);
}
return response.text();
}
In current browsers, creating an XHR object is direct:
const request = new XMLHttpRequest();
You do not need browser-specific object creation or ActiveX fallbacks for current web development.
The same request used above can be written with XHR. Encode the query parameter, check the HTTP status, and handle network failures.
function loadMessageWithXHR(name) {
const params = new URLSearchParams({ txt: name });
const request = new XMLHttpRequest();
request.open('GET', `ajax-get-testck.php?${params}`, true);
request.onload = function () {
if (request.status >= 200 && request.status < 300) {
console.log(request.responseText);
} else {
console.error(`HTTP ${request.status}`);
}
};
request.onerror = function () {
console.error('Network error');
};
request.send();
}
XHR acts as the browser-side request object between your JavaScript and a server endpoint. A typical request follows these steps:
XMLHttpRequest object.open() with the HTTP method and URL.send().| Feature | Fetch | XMLHttpRequest |
|---|---|---|
| Programming model | Promises / async-await | Event callbacks |
| HTTP error handling | Check response.ok | Check status |
| Progress events | Streaming APIs are needed for detailed progress | Built-in progress events are available |
| Existing older codebases | May require refactoring | Common in established AJAX code |
Very old versions of Internet Explorer created AJAX request objects through Microsoft ActiveX components. That compatibility code explains why older tutorials may contain ActiveXObject, but it is not needed in current browsers and should not be copied into new code.
Author & Instructor at plus2net
I write and maintain practical tutorials on Python, PHP, SQL, JavaScript, HTML, jQuery, and web development at plus2net. The tutorials focus on clear explanations, working examples, and code that readers can test and adapt while learning.