AngularT2_Light_1200x303

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.

  • What is XHR?
  • How to use XHR in JavaScript?
  • What is fetch?
  • How to use fetch in JavaScript?
  • Summary
  • Conclusion

What Is XHR?

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.

How To Use XHR Requests in JavaScript?

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:

  • onreadystatechange: This event is fired when readyState attribute changes its state.
  • abort: The event is fired when request is aborted.
  • error: The event is fired when request contains an error.
  • load: This event is fired when request is completed.
  • loadend: This event is fired when request is completed or gets error.
  • loadstart: This event is fired when request is loading the data.
  • progress: This event is fired when request gets data in chunks.
  • timeout: This event is fired when request is terminated because of time.

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:

  • abort: It aborts the request if already sent.
  • getAllResponseHeaders: It returns all response headers or null if no response.
  • getResponseHeader: It returns the particular header value by passing header name as parameter to it.
  • overrideMimeType: It overrides server sent type; we need to call this method before the open method.
  • send: It sends the created request to the server.
  • setRequestHeader: It sets the value for HTTP request header; we need to call it after open method.

Step 4: In the last step, we need to call the send method to send the request to the server:

xmlReq.send();

XHR Request Example

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

Articles by Jeetendra Gund, with a numbered list of linked article titles.

What Is Fetch?

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.

How To Use Fetch Request in JavaScript?

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

  • resource: In this parameter, you can pass the URL where you’re accessing the data or you can pass the Request object.
  • init: It is an optional parameter, but use it if you want to pass any other settings with a request object like method, body, headers, mode, credentials, redirect, etc. so you can pass like the code below:
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.

Fetch Request Example

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

We see the same list as before: Articles by Jeetendra Gund, with a numbered list of linked article titles.

Summary

In this article, we discussed both XHR and fetch, and how to use them to place requests to the server in JavaScript.

  • XHR is an old way make requests to the server. Fetch API is a modern way to make requests to the server.
  • Chaining is difficult in XHR, but in fetch you can easily chain the promises.
  • In XHR we need to check the status property for the errors, but in fetch the catch method is there to handle errors.

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
About the Author

Jeetendra Gund

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.

Related Posts

Comments

Comments are disabled in preview mode.