XMLHttpRequest vs the Fetch API: What's Best for Ajax in 2019?



Originally published at: https://www.sitepoint.com/xmlhttprequest-vs-the-fetch-api-whats-best-for-ajax-in-2019/

March 2019 celebrates the 20th anniversary of Ajax. Sort of. The first implementation of XMLHttpRequest shipped in 1999 as an IE5.0 ActiveX component (don’t ask).

Before then, there had been ways to pull data from a server without a full-page refresh, but they often relied on clunky techniques such as <script> injection or third-party plugins. Microsoft developed XMLHttpRequest primary for a browser-based alternative to their Outlook email client.

XMLHttpRequest was not a web standard until 2006, but it was implemented in most browsers. Its adoption in Gmail (2004) and Google Maps (2005) led to Jesse James Garrett's 2005 article AJAX: A New Approach to Web Applications. The new term crystallised developer focus.

AJAX to Ajax

AJAX is a mnemonic for Asynchronous JavaScript and XML. "Asynchronous" definitely, but:

  1. JavaScript was likely, although VBScript and Flash were options
  2. The payload did not need to be XML, although that was popular at the time. Any data format could be used and, today, JSON is normally preferred.

We now use "Ajax" as a generic term for any client-side process which fetches data from a server and updates the DOM dynamically without a full-page refresh. Ajax is a core technique for most web applications and Single-Page Apps (SPAs).

Extreme XMLHttpRequest

The following JavaScript code shows a basic HTTP GET request for http://domain/service using XMLHttpRequest (commonly shortened to XHR):

let xhr = new XMLHttpRequest();
xhr.open('GET', 'http://domain/service');

// request state change event
xhr.onreadystatechange = function() {

  // request completed?
  if (xhr.readyState !== 4) return;

  if (xhr.status === 200) {
    // request successful - show response
  else {
    // request error
    console.log('HTTP error', xhr.status, xhr.statusText);

// start request

The XMLHttpRequest object has many other options, events, and response properties. For example, a timeout in milliseconds can be set and detected:

// set timeout
xhr.timeout = 3000; // 3 seconds
xhr.ontimeout = () => console.log('timeout', xhr.responseURL);

and a progress event can report on long-running file uploads:

// upload progress
xhr.upload.onprogress = p => {
  console.log( Math.round((p.loaded / p.total) * 100) + '%') ;

The number of options can be bewildering and early implementations of XMLHttpRequest had a few cross-browser inconsistencies. For this reason, most libraries and frameworks offer Ajax wrapper functions to handle the complexity, e.g. the jQuery.ajax() method:

// jQuery Ajax
  .done(data => console.log(data))
  .fail((xhr, status) => console.log('error:', status));

Fast Forward to Fetch

The Fetch API is a modern alternative to XMLHttpRequest . The generic Headers, Request, and Response interfaces provide consistency while Promises permit easier chaining and async/await without callbacks.

Read more: https://www.sitepoint.com/xmlhttprequest-vs-the-fetch-api-whats-best-for-ajax-in-2019/