Welcome to The Coding College, where we make coding concepts clear and practical! In this tutorial, we’ll focus on the XMLHttpRequest Object, the core component of AJAX that allows you to interact with servers asynchronously. You’ll learn its properties, methods, and how to use it effectively in your projects.
What is the XMLHttpRequest Object?
The XMLHttpRequest (XHR) Object is a JavaScript API that enables communication between a web browser and a server. It is the foundation of AJAX, allowing you to send and receive data from a server without refreshing the entire page.
Why Use XMLHttpRequest?
- Asynchronous Communication: Fetch or send data without interrupting the user experience.
- Dynamic Content: Update parts of a web page dynamically.
- Flexible Formats: Supports data formats like XML, JSON, HTML, or plain text.
How Does XMLHttpRequest Work?
The XMLHttpRequest object works in a series of steps:
- Create an XMLHttpRequest Object: Use JavaScript to create an instance of XHR.
- Configure the Request: Specify the HTTP method (GET, POST, etc.) and the server URL.
- Send the Request: Send the request to the server.
- Handle the Response: Process the data returned by the server asynchronously.
Basic Syntax
Here’s the syntax for using the XMLHttpRequest object:
let xhr = new XMLHttpRequest(); // Step 1: Create an XHR object
xhr.open(method, url, async); // Step 2: Configure the request
xhr.send(data); // Step 3: Send the request
xhr.onreadystatechange = function () { // Step 4: Handle the response
if (xhr.readyState === 4 && xhr.status === 200) {
console.log(xhr.responseText); // Output the server response
}
};
XMLHttpRequest Properties
1. readyState
Indicates the state of the request:
Value | State | Description |
---|---|---|
0 | UNSENT | Request not initialized. |
1 | OPENED | Server connection established. |
2 | HEADERS_RECEIVED | Request received by the server. |
3 | LOADING | Processing request. |
4 | DONE | Request finished, response received. |
2. status
Indicates the HTTP status code of the response (e.g., 200 for success, 404 for not found).
3. responseText
Returns the response data as a plain text string.
4. responseXML
Returns the response data as an XML document (useful for XML-based applications).
5. onreadystatechange
A callback function that executes whenever the readyState
changes.
XMLHttpRequest Methods
1. open(method, url, async)
Initializes the request.
- method: The HTTP method (e.g., GET, POST).
- url: The server endpoint.
- async: Set to
true
for asynchronous requests (default).
2. send(data)
Sends the request to the server.
- Use
null
or leave blank for GET requests. - Pass data (e.g., JSON or form data) for POST requests.
3. setRequestHeader(header, value)
Adds a custom header to the request. Useful for sending content type or authorization tokens.
4. abort()
Cancels the current request.
Example: Simple GET Request
Let’s make a simple GET request using the XMLHttpRequest object.
HTML:
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>AJAX GET Example</title>
</head>
<body>
<h1>AJAX - XMLHttpRequest Example</h1>
<button id="fetchData">Fetch Data</button>
<div id="output"></div>
<script src="script.js"></script>
</body>
</html>
JavaScript (script.js):
document.getElementById("fetchData").addEventListener("click", function () {
const xhr = new XMLHttpRequest();
// Configure the request
xhr.open("GET", "https://jsonplaceholder.typicode.com/posts/1", true);
// Handle the response
xhr.onreadystatechange = function () {
if (xhr.readyState === 4 && xhr.status === 200) {
const response = JSON.parse(xhr.responseText);
document.getElementById("output").innerHTML = `
<h2>${response.title}</h2>
<p>${response.body}</p>
`;
}
};
// Send the request
xhr.send();
});
Example: POST Request with XMLHttpRequest
Here’s how to send data to the server using a POST request.
JavaScript:
const xhr = new XMLHttpRequest();
// Configure the request
xhr.open("POST", "https://jsonplaceholder.typicode.com/posts", true);
xhr.setRequestHeader("Content-Type", "application/json");
// Handle the response
xhr.onreadystatechange = function () {
if (xhr.readyState === 4 && xhr.status === 201) {
console.log("Response:", JSON.parse(xhr.responseText));
}
};
// Send the request with data
const data = JSON.stringify({
title: "New Post",
body: "This is the content of the post.",
userId: 1,
});
xhr.send(data);
Modern Alternatives: Fetch API and Axios
While the XMLHttpRequest object is powerful, modern developers often use the Fetch API or libraries like Axios for simpler syntax and improved readability.
Fetch API Example:
fetch("https://jsonplaceholder.typicode.com/posts/1")
.then((response) => response.json())
.then((data) => console.log(data))
.catch((error) => console.error("Error:", error));
Axios Example:
axios.get("https://jsonplaceholder.typicode.com/posts/1")
.then((response) => console.log(response.data))
.catch((error) => console.error("Error:", error));
Advantages of XMLHttpRequest
- Versatile: Works with any type of data (XML, JSON, HTML, plain text).
- Browser Support: Compatible with all major browsers.
- Low-Level Control: Offers detailed control over requests and responses.
Limitations of XMLHttpRequest
- Verbose Syntax: Requires more code compared to modern alternatives.
- Error Handling: Less user-friendly than the Fetch API or Axios.
- No Promises: Lacks built-in support for Promises, making it harder to manage asynchronous code.
Conclusion
The XMLHttpRequest Object is the foundation of AJAX and remains an essential tool for web developers. While modern APIs like Fetch simplify the process, understanding XMLHttpRequest helps you build robust, backward-compatible applications.