A Sprinkle of JavaScript

szam profile image Samuel Grasse-Haroldsen ・3 min read

API + JS = Single Page Application

Thanks to the power of Ruby On Rails we are able to quickly make a very robust back end; complete with models, views, and controllers. But we also have the option to skip the views and instead use Rails as an API and create a dynamic front end utilizing JavaScript and AJAX. Our back end won't look much different, but we can forget about creating views and we will now render our data in JSON.

Getting started

Our first command will create a new rails back end coupled with the api option which will allow us to generate resources without the views.

rails new app-name --api
Enter fullscreen mode Exit fullscreen mode

We will also have to set up CORS. Here is a brief definition from Wikipedia:

Cross-origin resource sharing (CORS) is a mechanism that allows restricted resources on a web page to be requested from another domain outside the domain from which the first resource was served.

The --api option we specified created a file titled 'cors.rb' with all the appropriate information commented out. All we have to do uncomment the body and specify which domain origins we are okay with accessing our server. We can just put a wildcard * to allow any domain access. We can also specify which resources, headers, and methods are allowed.

The back end

I like to start by setting up my database. We need to generate some migrations, some models, and controllers. None of these commands are any different from if we were not making an API.

rails g resource card
Enter fullscreen mode Exit fullscreen mode

As well as generating a migration, a model, and a controller this command also adds our usual RESTful routes to 'routes.rb'. Don't forget to add some data either in 'seeds.rb' or in your rails console.

Rendering JSON

JSON (JavaScript Object Notation) is an awesome, widely used format for sending information around the internet and other places! Some popular document-based databases even use it! The more comfortable we get with it the better! We can explicitly tell our rails controllers to render our data in JSON! After all we won't be rendering any of our own .erb.html files.

def index
  card = Card.find(params[:card_id])
  render json: card
Enter fullscreen mode Exit fullscreen mode

This will render our card's information in JSON format.

The front end

Now that we have our back end set up we can create our front end. We will need an HTML file, at least one JS file, and a CSS file. You don't technically need that much in your HTML file because JavaScript was created for DOM manipulation (you can add, edit, and remove elements from your webpage dynamically thanks to Brendan Eich).


AJAX is cool set of tools that allow content to be requested, received, and rendered all on the client side. It is an acronym for "Asynchronous JavaScript And XML." An asynchronous process allows a chunk of code to begin executing while other synchronous processes also execute. So without having to wait for our back end to send us the card we requested, we can render the rest of the page. Cool right?


The Fetch API provides a JavaScript interface for accessing and manipulating parts of the HTTP pipeline, such as requests and responses. It also provides a global fetch() method that provides an easy, logical way to fetch resources asynchronously across the network.

Straight from MDN. In simple terms fetch is an easy way for devs to utilize AJAX. The syntax is simple and here is something you would probably see in the wild:

        .then(r => r.json())
        .then(info => {
Enter fullscreen mode Exit fullscreen mode

This chunk of code requests information from our cards_controller's index method. And thanks to fetch we receive a response with our card's information along with some additional HTTP data. Using the .then keyword (a way of telling our browser to not execute the contents until the fetch has finished) we then convert that response (r) to JSON using r.json(). This is an example of what the converted JSON response might look like.

    "front":"Hello (informal to one person)",
Enter fullscreen mode Exit fullscreen mode

We then take our JSON info and send it to our addCards class method which will store all the cards we retrieved in an array so we can render them each to our page! Neat! Now our users can learn how to say hello informally to one person in Hungarian! The internet is a fun place! Szia can also mean goodbye so... Szia reader! Hope you enjoyed the article!


Editor guide