blog

  • Home
  • blog
  • A Guide to Vanilla Ajax Without jQuery

A Guide to Vanilla Ajax Without jQuery

Short for Asynchronous JavaScript and XML, Ajax is a mechanism for making partial page updates. It enables you to update sections of a page with data that comes from the server, whilst avoiding the need for a full refresh. Making partial updates in this way can be effective in creating fluid user experiences and can decrease the load put on the server.

This is the anatomy of a basic Ajax request:

var xhr = new XMLHttpRequest();
xhr.open('GET', 'send-ajax-data.php');
xhr.send(null);

Here, we are creating an instance of the required class to make an HTTP request to the server. We are then calling its open method, specifying the HTTP request method as the first parameter and the URL of the page we’re requesting as the second. Finally, we call its send method passing null as a parameter. If POST-ing the request (here we are using GET), this parameter should contain any data we want to to send with the request.

And this is how we’d deal with the response from the server:

xhr.onreadystatechange = function () {
  var DONE = 4; // readyState 4 means the request is done.
  var OK = 200; // status 200 is a successful return.
  if (xhr.readyState === DONE) {
    if (xhr.status === OK) 
      console.log(xhr.responseText); // 'This is the returned text.'
    } else {
      console.log('Error: ' + xhr.status); // An error occurred during the request.
    }
  }
};

The onreadystatechange is asynchronous, which means it gets called at any time. These types of functions are callbacks — one that gets called once some processing finishes. In this case, the processing is happening on the server.

For those wishing to learn more about the basics of Ajax, the MDN network has a good guide.

To jQuery or Not to jQuery?

So, the good news is that the above code will work across all the latest major browsers. The bad news is, well, that it is quite convoluted. Yuck! I am already pining for an elegant solution.

Using jQuery, one could condense the entire snippet to:

$.ajax({
  url: 'send-ajax-data.php',
})
.done(function(res) {
  console.log(res);
})
.fail(function(err) {
  console.log('Error: ' + err.status);
});

Which is nice. And indeed for many, including yours truly, jQuery has become the de facto standard when it comes to Ajax. But, do you know what? This doesn’t have to be the case. jQuery exists to get around the ugly DOM API. But, is it really that ugly? Or incomprehensible?

In the remainder of this article, I would like to investigate improvements made to the Ajax API in vanilla JavaScript. The entire specification can be found on the W3C. What strikes me about this specification is the name. It is no longer “XMLHttpRequest Level 2” but “XMLHttpRequest Level 1” — a result of a 2011 merger between the two specs. Going forward, it will get treated as a single entity from a standards perspective and the living standard will be called XMLHttpRequest. This shows that there is commitment by the community to stick to one standard, and this can only mean good news for developers who want to break free from jQuery.

So lets get started …

Setup

For this article, I am using Node.js on the back-end. Yes, there will be JavaScript on the browser and on the server. The Node.js back-end is lean, I encourage you to download the entire demo on GitHub and follow along. Here is the meat and potatoes of what’s on the server:

// app.js
var app = http.createServer(function (req, res) {
  if (req.url.indexOf('/scripts/') >= 0) {
    render(req.url.slice(1), 'application/javascript', httpHandler);
  } else if (req.headers['x-requested-with'] === 'XMLHttpRequest') {
    // Send Ajax response
  } else {
    render('views/index.html', 'text/html', httpHandler);
  }
});

This checks the request URL to determine how to the app should respond. If the request came from the scripts directory, then the appropriate file is served with the content type of application/javascript. Otherwise, if the request’s x-requested-with headers have been set to XMLHttpRequest then we know we’re dealing with an Ajax request and we can respond appropriately. And if neither of these is the case, the file views/index.html is served.

I will expand the commented out section as we dive into Ajax responses from the server. In Node.js, I had to do some heavy-lifting with the render and httpHandler:

Continue reading %A Guide to Vanilla Ajax Without jQuery%

LEAVE A REPLY