Especially for our Angular beginners, here’s a post about the difference between XHR and fetch, and how to use them.
In this article, we are going to learn how to use XHR and fetch request in JavaScript. This article covers the following topics.
XHR stands for XMLHttpRequest, and it’s an API we can use to make AJAX requests in JavaScript. Using this API, we can make a network request to exchange data from website to server. XHR is used to make HTTP requests in JavaScript, but it’s not the most modern approach.
XHR requests are an old way in JavaScript to place the HTTP requests with binding callback handlers, where methods will be called based on the state. Following are the steps to use XHR requests in JavaScript:
Step 1: To set up the HTTP request, we need to create an instance of XMLHttpRequest, as the code below shows:
// setup http request
var xmlReq = new XMLHttpRequest();
Step 2: Next, add the callback handlers or events to get the response from the HTTP request:
function onLoad() {
console.log(this.response);
}
// add callback handlers
xmlReq.addEventListener("load", onLoad);
In the above code, whenever the request is completed, the onLoad method gets the response in it.
Following are some more events:
Step 3: Next, we need to initialize the created request. For that, open method is used with parameters as code below shows:
Syntax
XMLHttpRequest.open(method, url[, async[, user[, password]]])
Use
xmlReq.open("GET", "https://my-json-server.typicode.com/JSGund/XHR-Fetch-Request-JavaScript/profile");
In the above code, we are placing the HTTP GET method request, so the first parameter is GET and the second parameter is URL from where we are planning to fetch the data.
Following are some more methods:
Step 4: In the last step, we need to call the send method to send the request to the server:
xmlReq.send();
In this demo example, we have placed the GET method and in the response we are getting a list of blogs in JSON format and we are parsing it. The returned response we have bound to the HTML ordered list, as you can see in the output.
xhr-request.html file
<!DOCTYPE html>
<html>
<head>
<title>XHR Request</title>
</head>
<body>
<div>
<h1>Article's by Jeetendra Gund</h1>
<div id="blogs"></div>
</div>
<script>
(function(){
var xhr = new XMLHttpRequest()
xhr.open('GET', 'https://my-json-server.typicode.com/JSGund/XHR-Fetch-Request-JavaScript/posts')
// get response here once request completes
xhr.onload = function() {
if (xhr.status != 200) {
console.log('Error')
return
}
var data = JSON.parse(xhr.response)
var html = '<ol>'
data.forEach(function(dt){
html += '<li style="font-size:22px;"><a href="'+dt.path+'">'+dt.title+'</a></li>'
})
html += '</ol>'
document.getElementById('blogs').innerHTML = html
}
xhr.onError = function() {
console.log('Request failed')
}
// send request to server
xhr.send();
})()
</script>
</body>
</html>
Output
Fetch is a modern way of making requests in JavaScript similar to XMLHttpRequest. Fetch is not based on callback handlers, it is based on promises. It is simple, readable and clean API code that is easy to understand.
The Fetch API uses the promise we need to resolve the response object, and for that we use the .then method after the fetch function. It returns the promise that contains response.
Syntax
fetch(resource [, init])
Parameters
fetch('sample.json',{
method: 'get',
mode: 'cors'
});
Example
fetch('https://my-json-server.typicode.com/JSGund/XHR-Fetch-Request-JavaScript/posts')
.then(response => response.json())
.then(function (response) {
console.log(response);
})
.catch(function (error) {
console.log('error', error);
});
In the above example you can see we have used two then
methods and a catch
method to catch the errors. In the first then
method, we get the response but it is not in readable format, so we have converted it into JSON. And with the second then
method we are getting the actual result in JSON format.
In this demo example, we have placed the GET method and in the response we are getting a list of blogs in JSON format. The returned response we have bound to the HTML ordered list, as you can see in the output.
fetch-request.html file
<!DOCTYPE html>
<html>
<head>
<title>Fetch Request</title>
</head>
<body>
<div>
<h1>Article's by Jeetendra Gund</h1>
<div id="blogs"></div>
</div>
<script>
(function(){
fetch('https://my-json-server.typicode.com/JSGund/XHR-Fetch-Request-JavaScript/posts')
.then(result => result.json())
.then(function (response) {
var html = '<ol>'
response.forEach(function(dt){
html += '<li style="font-size:22px;"><a href="'+dt.path+'">'+dt.title+'</a></li>'
});
html += '</ol>'
document.getElementById('blogs').innerHTML = html
})
.catch(function (error) {
console.log('error', error);
});
})()
</script>
</body>
</html>
Output
In this article, we discussed both XHR and fetch, and how to use them to place requests to the server in JavaScript.
You can download both the examples from here.
If you have any suggestions or queries regarding this article, please contact me using the links in my bio.
“Learn it, share it.”
Jeetendra Gund is a C# Corner MVP as well as the Chapter Leader of C# Corner Pune Chapter. He holds a master’s degree in Computer Science and has worked on several different domains. He has spent six years in grooming his knowledge about Microsoft Technologies and has been sharing his experiences on technologies such as C#.Net, MVC.Net, SQL Server, Entity Framework, AngularJS, JavaScript, HTML, and .NET Static Code Analysis. He is a regular speaker at C# Corner on Microsoft Technologies. Find him: C# Corner, LinkedIn, or Twitter.