AJAX - CreateXMLHttpRequestObject


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 a web page can be updated without reloading the entire web page.


Create an XMLHttpRequest Object

All modern browsers (IE7+, Edge, Firefox, Chrome, Safari, and Opera) have the XMLHttpRequest object built in.

Syntax for creating an XMLHttpRequest object:

var xhr = new XMLHttpRequest();

Old versions of Internet Explorer (IE5 and IE6) use ActiveX objects:

var xhr = new ActiveXObject("Microsoft.XMLHTTP");

In order to handle all modern browsers, including IE5 and IE6 (which are now rarely used), please check whether the browser supports the XMLHttpRequest object. If it does, create an XMLHttpRequest object. If not, create an ActiveXObject:

Example

var xmlhttp; if (window.XMLHttpRequest) { //IE7+, Firefox, Chrome, Opera, Safari browsers execute the code xmlhttp=new XMLHttpRequest(); } else { //IE6, IE5 browsers execute the code xmlhttp=new ActiveXObject("Microsoft.XMLHTTP"); }

Try it Yourself »

Example of creating an XMLHttpRequest object:

Example

// Create an 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) {
        // Handle the response when the request succeeds
        console.log('Response:', xhr.responseText);
    } else {
        // Handle errors
        console.error('Error:', xhr.statusText);
    }
};

// Handle network errors
xhr.onerror = function () {
    console.error('Request failed');
};

// Send the request
xhr.send();

In the next chapter, you will learn about sending requests to the server.

Other Extensions