Create XMLHttpRequest Object
In this step, you'll learn how to create an XMLHttpRequest object, which is the core mechanism for making asynchronous requests in JavaScript. We'll build upon the previous step's HTML file and add the XMLHttpRequest functionality.
Open the ~/project/ajax-demo.html
file in the WebIDE and update the script section to create an XMLHttpRequest object:
<!doctype html>
<html>
<head>
<title>XMLHttpRequest Demonstration</title>
</head>
<body>
<h1>AJAX Request Example</h1>
<button id="loadData">Load Data</button>
<div id="result"></div>
<script>
document
.getElementById("loadData")
.addEventListener("click", function () {
// Create XMLHttpRequest object
var xhr = new XMLHttpRequest();
// Log the creation of XMLHttpRequest object
console.log("XMLHttpRequest object created:", xhr);
});
</script>
</body>
</html>
Understanding XMLHttpRequest Object
The XMLHttpRequest
(XHR) object is a built-in browser API that allows you to:
- Create HTTP requests
- Send data to a server
- Receive data from a server
- Update parts of a web page without reloading
Key Methods of XMLHttpRequest
open()
: Initializes a new request
send()
: Sends the request to the server
onreadystatechange
: Tracks the state of the request
Browser Compatibility
XMLHttpRequest is supported in all modern browsers, making it a reliable choice for AJAX communications. Modern web development also uses the Fetch API, but XMLHttpRequest remains widely used.
Example Output
When you click the "Load Data" button, you'll see a console log demonstrating the creation of the XMLHttpRequest object:
XMLHttpRequest object created: XMLHttpRequest {...}