Introduction
We all are aware of JavaScript's dreaded XMLHttpRequest (XHR) request. Some developers are using XHR requests even today, which involves some very messy code. And really, the XHR request is not a pretty JavaScript code. It might be possible that you are using jQuery to send the XHR which is cleaner but not the best.
jQuery XHR Request Syntax
Now, we have JavaScript's built-in Fetch API by which you can make requests similar to that of XHR.
Fetch API
Fetch API allows you to make network requests similar to XHR. It has a new standard jam-packed way to make the request, which also uses promises.
Before starting with Fetch API, let's understand how XHR request works.
Using XMLHttpRequest
To send an HTTP request, first, we create XMLHttpRequest Object. By this object, we open the connection using the URL and send the request. After the transaction completes, we also create some event listeners by which we get the response back with HTTP Status Code.
XMLHttpRequest Example
- function progress() {
- ...
- }
-
- function success(data) {
- ...
- }
-
- function error() {
- ...
- }
-
- function canceled() {
- ...
- }
-
- var req = new XMLHttpRequest();
- req.addEventListener("progress", progress);
- req.addEventListener("load", success);
- req.addEventListener("error", error);
- req.addEventListener("abort", canceled);
-
- req.open("GET", "/GetData");
- req.send();
XMLHttpRequest with jQuery
The following example shows how you can send xhr request using jQuery.
- jQuery.ajax({
- url:url,
- type:'POST',
- data:JSON.stringify(data),
- dataType:'json',
- contenttype:'application/json',
- beforeSend:function(xhr){
- ...
- },
- success:function(data){
- ...
- },
- error:function(data){
- ...
- },
- complete:function(){
- ...
- }
- })
How do we use the fetch API?
In a very simple manner, we can call Fetch API with URL only. By default, the Fetch API uses the GET verb. Let's look at a very simple single line example:
Simple fetch API syntax
- fetch(url).then(() => {
- ...
- }).catch(() => {
- ...
- })
Let's understand what syntax is
- fetch(url)
- .then((data) => {
-
- })
- .catch((err) => {
-
- })
Example
- fetch('https://freegeoip.net/json/github.com')
- .then((res) => res.json())
- .then((data) => console.log(data))
Let's understand the above code. In the above code, first, we are calling Fetch API and passing it to the URL. We are not passing more parameters, so by default, the call will be a GET call. Then, we get a response but it is not JSON but an object. So, we are converting the object into JSON using the json() method. Then, we are printing the JSON result.
There are a series of methods like json() which we can use depending on the situation, what we want to do with the information. Those methods are as follows,
- arrayBuffer()
Returns a promise object with an Array Buffer.
- blob()
Returns a promise object with a blob object.
- clone()
This creates a clone of the response.
- formData()
Returns a Promise that resolves with FormData object.
- json()
Returns a promise with a JSON object.
- redirect()
This method creates a new response but with a different URL.
- text()
This method is used when want to resolve object into text.
In the above example, we saw how to GET the data using Fetch API. Now I know you are excited and thinking about POST, PUT, and DELETE calls. I am going to explain POST calls; then I know you will be able to call any http verb.
POST call using Fetch API
By default fetch API uses GET request. You can use the following syntax for the POST call.
- const url = '<URL>';
-
- let data = {
- name: 'sourabh somani',
- email: '[email protected]',
- mobile: '9314554546'
- };
-
- fetch(url, {
- method: 'POST',
- body: data,
- headers: new Headers()
- }).then(function(res) {
-
- }).catch(function(err) {
-
- });
You can read more about fetch API from the following links,
- https://developers.google.com/web/updates/2015/03/introduction-to-fetch
- https://developer.mozilla.org/en-US/docs/Web/API/Fetch_API
Conclusion
Fetch API is better and simpler to use than XHR. So, don't use XMLHttpRequest anymore. Instead, you can use Fetch API.