In the early days of web development, before the introduction of more modern APIs like fetch
or third-party libraries such as Axios, developers primarily relied on XMLHttpRequest
for data fetching in JavaScript. Though it may seem outdated in 2023, XMLHttpRequest
remains an essential part of the history of the web, and understanding it can provide insights into how asynchronous operations work under the hood.
Getting Started with XMLHttpRequest
To initiate a data request using XMLHttpRequest
, the basic structure is as follows: you create an instance of XMLHttpRequest
, set up an event handler to process the server response, and then make the request using the open
and send
methods.
Basic Example
var xhr = new XMLHttpRequest();
xhr.open("GET", "https://jsonplaceholder.typicode.com/posts", true);
xhr.onload = function() {
if (xhr.status >= 200 && xhr.status < 300) {
console.log(xhr.responseText);
} else {
console.log('Request failed with status: ' + xhr.status);
}
};
xhr.send();
In the above example, a GET
request is made to a public API endpoint. We specify the HTTP method and URL with xhr.open()
and use the onload
event to handle a successful response.
xhr.responseText
contains the data returned from the server, which is available as a string. Note the use of status codes to verify a successful response (typically, 2xx codes indicate success).
Handling Different Response Types
The XMLHttpRequest
object offers flexibility when dealing with different data formats, such as plain text, XML, or JSON.
Parsing JSON Responses
xhr.onload = function() {
if (xhr.status === 200) {
var jsonResponse = JSON.parse(xhr.responseText);
console.log(jsonResponse);
} else {
console.error('Failed to fetch data');
}
};
Here, we parse the response as JSON using JSON.parse()
, making it easy to work with JavaScript objects.
Retrieving XML Data
Similarly, for XML responses, the responseXML
property provides us with a Document object to easily traverse XML nodes.
xhr.onload = function() {
if (xhr.status === 200) {
var xmlData = xhr.responseXML;
console.log(xmlData.getElementsByTagName("title")[0].childNodes[0].nodeValue);
}
};
Handling Errors and States
Error handling is vital when performing network requests. The XMLHttpRequest
has an onerror
event to handle network errors, and you can monitor upload/download progress with onprogress
.
xhr.onerror = function() {
console.error('Network error occurred');
};
The readyState
attribute helps in understanding the progress of the request, ranging from 0 (uninitialized) to 4 (request completed and response is ready).
Advanced Usage
Besides basic GET requests, XMLHttpRequest
supports more complex operations such as POST requests and setting headers for requests.
Sending Data with POST
var xhr = new XMLHttpRequest();
xhr.open("POST", "https://your-api-endpoint.com");
xhr.setRequestHeader("Content-Type", "application/json;charset=UTF-8");
xhr.onload = function() {
console.log(xhr.responseText);
};
xhr.send(JSON.stringify({ title: 'foo', body: 'bar', userId: 1 }));
In this example, we prepare a request to send JSON data to a server by setting the appropriate Content-Type
header.
Conclusion
Now that you have a better understanding of how XMLHttpRequest
works, it should furnish you with a solid foundation when diving into asynchronous operations in JavaScript. While modern alternatives like the fetch
API are favored for their simplicity and promise-based approach, knowing how to operate with XMLHttpRequest
remains invaluable for working in legacy systems and offers deeper insight into the web's asynchronous capabilities.