Since JavaScript is a single-threaded language, it is synchronous in nature. So doing the asynchronous tasks was a pain in the ... Therefore the concept of AJAX was introduced in javascript. Fetch and XHR is two popular methods that use AJAX.
AJAX
Prior to the introduction of the AJAX
(Asynchronous JavaScript and XML) idea, to update a piece of a page, browsers would send a request to the server for a full web page, which the server would then construct and present to the browser as a response. It signifies that the page was completely loaded, even if only for a tiny modification. Wasn't that a disaster? It's terrible.
When AJAX
first appeared on the internet, it revolutionized the way pages were updated. Web applications could transmit and get data from a server asynchronously using AJAX
without interfering with the present page's appearance and behavior.
The term AJAX
refers to methods for loading server data from a client-side script. Over the years, a variety of choices have been provided. Most JavaScript frameworks will employ one or both of the two primary approaches. These two methods are XHR and Fetch.
XHR(XMLHttpRequest)
In 2006, W3C published the first Working Draft specification for the XHR
object.
Although the XHR's original concept was developed by Microsoft in somewhat 1999.
XHR object returns data from a server asynchronously. XMLHttpRequest got this name because in the early days it used to retire XML
data over Http
. As time progress, support for HTML
, JSON
also included.
Let's see how to use XHR.
const url = "https://jsonplaceholder.typicode.com/users";
const xhr = new XMLHttpRequest();
xhr.open('GET', url);
xhr.onload = () => {
console.log(JSON.parse(xhr.response)
}
xhr.onerror = ()=>{
console.log("Error !!!")
}
xhr.send();
XHR Interface
Have a look at the above code snippet and let us understand how it works.
- In the first line we create a URL variable to store the URL to which we are sending a request.
- Next, we a creating a
XHR
object using a pre-defined method XMLHttpRequest() in javaScript. - Now we use
xhr.open()
to open a request. it takes two parameters, one is the method and another one is the URL. In the given scenario we are using theGET
method. - Next, we have
xhr.onload()
which is an event listener and takes a callback function, which is called whenever we receive a response from the server. - As the name suggests,
xhr.onerror()
is also an event listener and takes a callback function but gets called only when an error is encountered. - At last
xhr.send()
is used to send requests to the server.
Axios
is a Javascript library used to make HTTP requests and has supports for the Promise API which is a modern Javascript feature. If we see the source code of Axios we can see that it uses XHR for HTTPS requests under the hood.
Fetch
We need something new as the old one can keep up with the present world scenarios and that is what happens with the
XHR
and theFetch
was born.
Fetch is a fairly new Promise-based AJAX
request API that debuted in 2015 and is now supported by the majority of browsers. It isn't based on XHR and has a more consistent and simple syntax. Fetch makes it easier to make asynchronous requests and handle responses better than with the older XHR. Also since it is promised based it solves the problem of Callback hell
.
Fetch Interface
The Fetch API is made up of the following interfaces.
fetch()
: The fetch() method is used to retrieve a resource.Headers
: Represents request/response headers, allowing you to query them and take various actions based on the results.Request
: A resource request is represented by this object.Response
: The response to a request is represented by this object.
Fetch Method
In the global window object, there is a fetch()
function. It takes one mandatory argument which is the URL path. A promise is returned whether the fetch call succeeds or fails. If calls succeed, the then()
method will receive the Response object and if it fails, the error object will be passed to the catch()
function.
Fetch also take a second optional parameter that is used to customize the request.
Fetch Call Code Snippet
fetch("URL", { method: "GET" })
.then(res => console.log(res))
.catch(err => console.error("error:", err));
The Response Object
The above code makes a call to the URL. When the promise is fulfilled, we are given a Response object. If we console.log(res)
, it will return the data about the response and the desired data that we want. So, We need to get the body of the response in order to get the data.
Let's see how that can be done.
The returned response has a .json()
method. All we have to do now is use the .json()
function on the response variable. Also, we need another .then()
method as .json()
function will return a promise.
fetch("URL", { method: "GET" })
.then((res) => res.json())
.then((json) => console.log(json))
.catch(err => console.error("error:", err));
And the above code will return the data that we want.
Headers Object
The Headers allow us to create our own headers object via the Headers() constructor. A header object is a collection of name-value pairs.
const customHeaders = new Headers({
'Content-Type': 'text/json',
'X-Custom-Header': 'SomeValue'
});
Conclusion
I can only think of one scenario where
XHR
is might help that is if We want to support very old browsers.
As it is evident XHR
is an older one. We also know that the newer Fetch
exists because the older one has shortcomings. So for the current situation, it's better to use fetch in my opinion as it is easier to make asynchronous requests and handle responses. Also, fetch uses modern javaScript features such as promises, which help us to create a better API for simple things.
Links and Resources ๐
For more clarity, you can watch Fetch and XHR
First of all thank you for reading. ๐Hope you all have learned something. This is my attempt to pen down what I understand of the topic. Please let me know if there are any errors and also how can i improve. You can reach out to me on Twitter and LinkedIn