AJAX, Express, MongoDB — Part 1: AJAX


So here we are in week two of code school. Things are moving quite quickly, and this article will attempt to describe what we’ve learned about AJAX in the past week.

When we want to make get some information from an API, we use AJAX to handle the call and response. We start by typing $.ajax() and then pass in two parameters — the url of our particular API call and an object containing references to handler functions for success or error. Altogether it looks like this:

$.ajax(API_CALL_URL, {
success: successHandler,
error: errorHandler,
});

Assuming the API itself is currently functioning properly, the AJAX call returns either a JSON object or an error object, which are passed into their respective handler function calls. With the error handler, we can can retrieve the status code from the error object with error.status and display it to the user along with a brief explanatory message. With the success handler, we can access the information contained within the JSON object that we receive.

By entering the API call directly into our browser address bar, we can look at the JSON object through the console. Looking it over, we can see what particular data we have to work with (for example, sub-objects that contain data that we want), and access that data in our success handler like this:

function successHandler(data) {
  data.subObject.particularData
}

In the example we built in class, the JSON object we retrieved contained links to images and descriptive tags for each image. It should be noted that there was a ton of other data in each object, but we were only interested in the images and tags. Once we identified the key: value pairs that led us to the images and tags, we could do things with them in our javascript code, which in our case we parsed them into an HTML template (a “card” from Bootstrap) which we inserted into an empty set of <div id="image-container">tags in our HTML code via a JQuery DOM insertion:

$('#image-container').append(htmlTemplate);

At this point, basically we’re all set: we were able to use AJAX to make an API call and get a JSON object back.

One other thing of interest that might be noted, briefly, is that we can make unique API calls using an event listener on an HTML text input. Once we’ve pulled the input into our javascript, we can parse the input text into a custom URL that we build to feed into our AJAX call. For our in-class example, building that new custom URL looked like this:

And to bring it all back around, we make our AJAX call with our custom completeURL:

$.ajax(completeURL, {
  success: successHandler,
  error: errorHandler,
});