Describe the XMLHttpRequest object and its role in AJAX. Provide a code example demonstrating its use.
The `XMLHttpRequest` object is a key component of AJAX (Asynchronous JavaScript and XML), which enables web pages to communicate with a server without requiring a full page reload. This allows developers to update parts of a web page asynchronously, improving user experience by making applications more dynamic.
### Role of `XMLHttpRequest`
1. **Asynchronous Communication**: The `XMLHttpRequest` object allows a client (browser) to send requests to and receive responses from a server asynchronously, meaning that other operations can continue running in the browser while waiting for a server response.
2. **Data Formats**: Although named after XML, the `XMLHttpRequest` object can handle various types of data, including JSON, plain text, and HTML.
3. **HTTP Methods Support**: It supports various HTTP methods such as GET, POST, PUT, DELETE, etc., allowing different types of interactions with the server.
4. **Handling Response**: Developers can specify callback functions to handle the server’s response, making it possible to manipulate the HTML of the web page dynamically based on that response.
### Code Example
Here's a simple example that demonstrates how to use the `XMLHttpRequest` object to fetch data from a server and update the content of a web page without reloading it. In this case, we'll request data from a placeholder API that returns user information in JSON format.
```html
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>AJAX with XMLHttpRequest</title>
<script>
function fetchUserData() {
// Create a new XMLHttpRequest object
var xhr = new XMLHttpRequest();
// Configure it: GET-request for the URL
xhr.open('GET', 'https://jsonplaceholder.typicode.com/users/1', true);
// Set up a function to handle the response
xhr.onreadystatechange = function () {
// If the request is complete
if (xhr.readyState === XMLHttpRequest.DONE) {
// Check if the request was successful
if (xhr.status === 200) {
// Parse the response text (JSON)
var user = JSON.parse(xhr.responseText);
// Update the DOM with user data
document.getElementById('userData').innerHTML =
'<h3>' + user.name + '</h3>' +
'<p>Email: ' + user.email + '</p>' +
'<p>Phone: ' + user.phone + '</p>';
} else {
console.error('Error: ' + xhr.status);
}
}
};
// Send the request
xhr.send();
}
</script>
</head>
<body>
<h1>Example of XMLHttpRequest</h1>
<button onclick="fetchUserData()">Fetch User Data</button>
<div id="userData"></div>
</body>
</html>
```
### How It Works
1. **Creating the Request**: The `XMLHttpRequest` object is created using `new XMLHttpRequest()`.
2. **Configuring the Request**: The `open` method is called to configure the request. In this example, we are using the GET method to fetch user data from a placeholder API.
3. **Handling the Response**: The `onreadystatechange` event is used to define a function that will execute whenever the `readyState` changes. When the request completes (`readyState` equals `XMLHttpRequest.DONE` which is 4), we check the status of the response. If successful, we parse the JSON data and manipulate the DOM to display it.
4. **Sending the Request**: Finally, we call the `send` method to send the request to the server.
This example showcases how you can easily make asynchronous requests using the `XMLHttpRequest` object, facilitating smooth user interactions on web applications.