AJAX Basics - XHR, Fetch, jQuery, & Axios

How-To Reference

Continuing in my latest course today we picked up with AJAX and learned a few things.

AJAX

AJAX allows you to get and load data from a server to an already-loaded page without reloading that page. There are a few different ways to make AJAX requests:

XMLHTTP Requests

XMLHTTP requests (XHR for short) are AJAX in its rawest, native form. The basic syntax is:

// Initiate a request
var XHR = new XMLHttpRequest();

// Do something every time the "ready state" changes (codes 0-1-2-3-4)
XHR.onreadystatechange = function() {
// ...only if a response has come back without error
if (XHR.readyState == 4 && XHR.status == 200) {
console.log(XHR.responseText);
}
};

XHR.open("GET", "https://api.github.com/zen");
XHR.send();

To test this I wrote a Bitcoin price checker which calls an API and updates the price with the click of a button. Then, because this is old and clunky, we learned some newer ways to accomplish the same thing…

Fetch API

Update June 2019: This David Walsh blog post is another good go-to reference for using the fetch API. It covers its usage a lot more deeply and includes some gotchas.

And the syntax is much cleaner!

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

To test this I wrote another Bitcoin price checker using Fetch instead of XHR.

Beyond these basics, there are some additional options that can be used with the Fetch API. While the first argument will always be a url, options can be passed in as a second argument, within an object:

fetch(url, {
method: "POST",
body: JSON.stringify({
name: "Nia",
login: "Bia"
})
})
.then(function(res) {
// Do something with res
})
.catch(function(err) {
// Handle error
})

More info about using options to change headers and HTTP request types, etc. can be found in the docs.

One thing to note about error handling: catch will only throw an error if there is an error with the request itself—not if there is an error in the response, like a 404 error to the fetch url for example. So we should handle response errors in the fetch request too:

fetch(url)
// Handle response errors
.then(handleErrors)

// Handle response success
.then(function(response) {
console.log(response);
})

// Handle request errors
.catch(function(error) {
console.log(error);
});

function handleErrors(request) {
if (!request.ok) {
throw Error(request.status);
}
return request;
}

We wrapped up the section with one more Fetch demo putting all of this together.

But… not all browsers support fetch() so we learned some other AJAX tools…

jQuery AJAX

jQuery uses the method $.ajax() as a shortcut for the XHR described above. There are some additional AJAX shortcut methods—$.get(), $.post(), and $.getJSON()—which also call $.ajax() under the hood. The basic syntax is:

$.ajax({
method: "GET", // GET is default
url: "some.api.endpoint",
dataType: "json" // Optional. By default it will guess based on result.
})
.done(function(response) {
// Do something with the response
})
.fail(function() {
// Handle error
})

I wrote a random cat pic generator to play with the $.getJSON() method.

Axios & AJAX

Another alternative that’s compatible with more browsers, but less cumbersome than including the entiiiire jQuery library is Axios. The Axios library (which can be included from a remote host: <script src="https://unpkg.com/axios/dist/axios.min.js"></script>) makes XHR requests, automatically parses JSON data, and can be used with Node.js using the same syntax as front-end code. The basic syntax is:

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

function handleErrors(err) {
if (err.response) {
console.log("Problem with response: " + err.response.status);
} else if (err.request) {
console.log("Problem with request!");
} else {
console.log("Error: " + err.message);
}
}

Note the different error handling for Axios: it’s built in to determine where the error is being generated so you can form the appropriate responses more easily.

To wrap it all up I wrote AJAX calls using all 4 methods in one quote generator.

Other Stuff

Today I went to a pair programming event and got to work on some algorithm challenges with someone. We had a good time! The more I do it, the more I think pairing success really comes down to the two people in the pair being a good fit, regardless of the skill level of either person.

Up Next

There are so many things I want to get done! I realized the other day that a site I manage is up for renewal in 4 weeks…I got a good deal for the first year but the price will go up dramatically so I want to move it before then. But since it’s a WordPress site I want to basically re-build it from scratch using a static site generator. But to do that I want to use CSS Grid so I have to learn that first! And I also really want to try using Gatsby as the gennie, which means I need to learn React, which means I need to finish this course asap. Realistically, I don’t think I can do all of this and build the site in a month!! :(