Ajax At Your Service

When learning AJAX first showed up on my calendar, this was all I could think of:

Aptly named for hero of the Trojan Wars, because of course it is.

Which has zero things to do with what we are going to actually talk about here. Asynchronous Javascript and XML or Ajax, in layman’s terms, exchanges requested data with a server to update the webpage; the kicker is, it works without having to reload the entire page.

Lil’ bit of info:

  • Asynchronous: Two or more events are existing or happening at the same time. For example, when click on a button, like adding a head of lettuce to your shopping cart, this can happen independently of your other actions.
  • Javascript: The language we’re writing our requests in (jQuery is a popular Javascript library you’ll most likely be using)
  • XML/JSON: Data transferred in the request

One example of an Ajax request is when you’re rating a show on Netflix in your profile. You can move quickly from flick to film to TV show, tossing out ratings in bulk, instead of rating one show and refreshing each time, which would slow you down, and you would have never found all the seasons of SVU which is in of itself, a modern day tragedy.

Olivia Benson for President

Anyway, Let’s take a look at an example of an Ajax request pulling from the City of Chicago’s data.

function getData(){
var landmarksDiv = document.getElementById('landmarks');
$.get('https://data.cityofchicago.org/resource/fpx9-pjqk.json', function(landmarks){
All hail the BEAN

On our first two lines we’re creating a function to pull out the Landmarks of Chicago by their unique ID’s. The good stuff is the next part.

“$” defines that we are using jQuery. Next, is our “get” request which we can also use “post” for, this selector finds our HTML elements. Next we’re calling the API, and pulling out that JSON to populate our page.

And we did all of that without refreshing.

not to brag or anything…