Create XMLHttpRequest object using AJAX
AJAX - Create XMLHttpRequest object
XMLHttpRequest is the foundation of AJAX.
XMLHttpRequest object
All modern browsers support the XMLHttpRequest object (IE5 and IE6 use ActiveXObject).
XMLHttpRequest is used to exchange data with the server in the background. This means that a part of the webpage can be updated without reloading the entire page.
Create XMLHttpRequest object
All modern browsers (IE7+, Edge, Firefox, Chrome, Safari, and Opera) have a built-in XMLHttpRequest object.
Syntax for creating an XMLHttpRequest object:
var xhr = new XMLHttpRequest();
Older versions of Internet Explorer (IE5 and IE6) used ActiveX objects:
var xhr = new ActiveXObject("Microsoft.XMLHTTP");
To support all modern browsers, including IE5 and IE6 (which are rarely used now), check if the browser supports the XMLHttpRequest object. If it does, create an XMLHttpRequest object. If it does not, create an ActiveXObject:
instance
var
xmlhttp
;
if
(
window
.
XMLHttpRequest
)
{
//
IE7+, Firefox, Chrome, Opera, Safari browser executes code
xmlhttp
=
new
XMLHttpRequest
(
)
;
}
else
{
//
IE6, IE5 browsers execute code
xmlhttp
=
new
ActiveXObject
(
"
Microsoft.XMLHTTP
"
)
;
}
Try it »
Example of creating an XMLHttpRequest object:
Instance
// Create XMLHttpRequest object
var
xhr
=
new
XMLHttpRequest
(
)
;
// Configure the request
xhr.
open
(
'GET'
,
'https://api.example.com/data'
,
true
)
;
// Set request headers (if needed)
// xhr.setRequestHeader('Content-Type', 'application/json');
// Define callback function
xhr.
onload
=
function
(
)
{
if
(
xhr.
status
=
200
&&
xhr.
status
<
300
)
{// Request successful, process response
console.
log
(
'Response:'
,
xhr.
responseText
)
;
}
else
{
// Handle error
console.
error
(
'Error:'
,
xhr.
statusText
)
;
}
}
;
// Handle network errors
xhr.
onerror
=
function
(
)
{
console.
error
(
'Request failed'
)
;
}
;
// Send request
xhr.
send
(
)
;
In the next chapter, you will learn about sending server requests.