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