The XHR History Lesson You Never Wanted

Written by jc.haines19 | Published 2017/11/19
Tech Story Tags: javascript | http-request | ajax | tech | xhr-history-lesson

TLDRvia the TL;DR App

Despite its nature as a single threaded language, one of JavaScript’s greatest strengths is its ability to make asynchronous requests — AJAX.

Take an application like Instagram or Pinterest for example. How is it that I can continue scrolling forever and ever, without a page reload, and content continues to show up? What’s happening behind the scenes is this asynchronous request to a server that does not end up disturbing the user? Around 2005 (when the term AJAX was coined), this was pretty revolutionary. Since then, new technologies have been built on top of older ones to create a more useful, faster web.

How Did We Get There Though? Enter XHR

On Chrome or other browsers, if you were to inspect any page, you could head over to the Network tab, then notice a sub-tab called XHR. Within this tab, you could see the status of requests, how long requests take, and plenty more. In fact, this tab becomes more interesting when you use it on a page like mentioned above (Instagram or Pinterest), because you could actually see AJAX at work, every time the page hits the bottom and sends another request to the server.

But how did this all start?

XHR is short for XMLHTTP Request. While developed by Microsoft’s Outlook Web Access, some of the earliest instances of this type of request were used in your Gmail inbox. It was pretty revolutionary to see your inbox update without having to refresh your page. The way it worked was every 20–30 seconds, a new request was sent to see whether or not you had new mail.

How exactly do you write this request:

var XHR = new XMLHttpRequest();

XHR.onreadystatechange = function() {if(XHR.readyState == 4) {if(XHR.status == 200) {console.log(XHR.responseText);} else {console.log("Error!");}}}

XHR.open("GET", "url");XHR.send();

The code above is a lot to wrap your head around, but remember, this is before newer, quicker methods were built on top of making requests.

What’s funny about this request is that while XML is written in all-caps, HTTP is not — probably done just to keep you confused. Another unfamiliar part of this piece of code is line 3: what is the readyState and why should it equal 4? Ready state is a property and giving it the label of 4 is a way of signaling that the fetch operation is complete.

Fetch

Making a request can be done in a lot of ways. Its the standard way of computers interacting with one another. So it’s only right that the bulky code from above was eventually built upon. Fetching for data is done in a much more condensed way (seen below) using promises that can be chained and made much more complex.

fetch(url).then(function(res){console.log(res);}).catch(function(error){console.log(error);});});

What’s cool about the Fetch request is that it provides options that could be included that weren’t initially possible when the XHR was running the show. Observe below, the same fetch request, only now with an additional object that contains a POST request, as opposed to the default GET we’ve been seeing so far.

fetch(url, {method: 'POST',body: JSON.stringify({username: 'Ajax_Hero_123',password: 'iwantarmor',})}).then(function(res){console.log(res);}).catch(function(error){console.log(error);});});

Fetch’s biggest drawback is browser compatibility, most notably with Internet Explorer. But the main takeaway is that it made the XHR smoother and more concise and allowed for more options. Like many other parts of the web, it’s a perfect example of how these technologies weren’t made in a vacuum, rather, in conjunction with one another. Which brings us to the next part of the journey.

Dollar Signs and other Third Parties

If you’ve heard of JavaScript, chances are, you’ve come across jQuery, the most popular third-party library of all time. While anything can be done in vanilla JavaScript, jQuery’s ability to create more concise code is huge, most notably when making an AJAX request.

Remember that big chunk of code up top, where we made an XML HTTP Request that took multiple lines of code, an if statement to check what readyState we were in, an if statement to make sure we were getting back a 200 status, parsing of the JSON data we received, and a dot send to finally make sure the code does what it is supposed to do?

Here is the same code, done with jQuery:

$.getJSON('/my/url', function(data) {

});

I would say that’s an improvement.

If you aren’t familiar with jQuery, also note that any instance of a dollar sign can be substituted for the word jQuery. My impression is that time is money, and saving you time from writing that big chunk of code would allow you to waste your time in other ways, hence the dollar sign.

jQuery is a fantastic library for many reasons, including making AJAX requests. It was created in 2006, and has since taken off. But what if you only wanted to use jQuery for these requests but nothing else? For this, there are other third party libraries, such as Axios, whose main focus is making request and nothing else. So, if you don’t need jQuery to make that fadeIn animation, your code will thank you for using something a little more lightweight.

Here is what Axios looks like in practice:

axios.get(url).then(function(res){console.log(res.data);}).catch(function(error){console.log(error);})

Ajax’s untimely end came when he threw himself on his own sword

Axios has the distinction of being able to make HTTP requests from Node.js. It also automatically parses JSON data, so there is no need to include an extra line of code that does such in a promise.

Wrapping up, it’s amazing to see how far the web has gone in a bit over a decade. These four ways of making requests are all just XML HTTP requests, as you could tell within your developer tools, but carry more capabilities (such as streaming, something not in the initial XHR back in 2005) and will only continue to get better with more cool libraries.

📚 Thanks for reading and follow me if you enjoyed this article 📚


Published by HackerNoon on 2017/11/19