How much does your professor make? Pt.2

Eduardo Poleo
Influitive Crafters

--

In my previous post we scraped some data and dumped it into three different endpoints, effectively converting our simple application into a JSON api. In this post I am going to show how we can use use AJAX and D3 to retrieve this data and render our view elements, which in this case are going to be awesome dynamic plots.

In addition to our JSON end-points we are also going to need an endpoint to serve our html and assets (js and css files). Our route file can then look similar to this:

We want to link each route to a radio button so that users can switch between different datasets. So we are going to add a radio button menu to our main view:

We don't really need to set any specific form action/route in the form_tag because we are not going submit the form. Instead, we are going to hijack the click event and then perform an AJAX call to retrieve the corresponding dataset.

Note how the radio buttons have a class choice and their values are set to match the routes where we are dumping the JSON data (e.g all_salaries). This is intentional as we want to simplify our javascript logic down the road.

We can then write the ajax code that we are going to use to retrieve the data from the JSON endpoints.

Because of the way D3 works we will need to use our ajax_call function in two different cases: when we first draw the plot, and when we update it after the user clicks one of the radio buttons. In order to dry out our code we can make the ajax_call accept a callback function for each case.

Now that we have wired up the data retrieval to the radio buttons, we can start writing our actual D3 code. First we will need to do define some general parameters and create some reusable functions:

NOTE: I do not intent to go into details on how D3 works in this post. This is a very big topic deserving of a entire book. I will add the code in this post for completeness but the idea of this specific series is to show how we can we deviate from the conventional rails rendering to use more interactive js libraries such D3.

Every time we update our plot we will need to recalculate the scales and axes to account for differences in each dataset (number of points, max values, etc). Thus, it makes sense to create reusable functions so that we are not repeating this code all over the place.

With the set up in place we can write up our draw and update functions which ultimately will do the heavy-lifting when drawing the plots.

The update function will get triggered every time the user clicks on a radio button. Its main responsibility will be to dynamically update the rectangles, axis and scales to account for changes in the dataSet.

You can check out the final result in here and the full code is on this repo.
Hope you guys enjoyed this short series on Rails/JSON/APIs and JS front-end rendering!

Happy Coding.

--

--