Ajax on Rails step by step

My previous post about Ajax was aimed to people who knows how to actually make an Ajax solicitation, but this is not the case for people who are beginning. So, I’ll explain better how to do this. I’ll teach it using CoffeeScript and JSON, but you are free to trade technology as much as you want (using Javascript and XML, for example).

What is an Ajax solicitation?

I’m going to be really objective here: an Ajax solicitation happens when you want to request some data from the server (or send it) without reloading the page, and process it with a Javascript callback.

For doing this, you must do three things:

  1. Your server must provide the data via HTTP;
  2. You must make a solicitation;
  3. You must have a callback function for when the solicitation arrives

Provide data via HTTP

That’s really simple. The server does not care if the solicitation is Ajax or not, so every data the server provides you can be retrieved in Ajax. For example, let’s say you have this controller:

class FriendsController < ApplicationController
  def show
    @friend = Friend.find(params[:id])

    respond_to do |format|
      format.json { render json: @friend }

You can retrieve a JSON representation of the friend with id 1 with “GET /friends/1.json”. It doesn’t matter if you requested it from a regular link or an Ajax link, the server will send you the same JSON.

So, it’s really easy on the server side: you can simply remain with your current controllers. At most, add JSON representations to your resources.

Make a solicitation

Generally, an Ajax solicitation is more confuse and obscure. Not on Rails. If you want a link to make an Ajax solicitation, you just have to add the “remote” attribute to it.

For example, if you want to make a link to make an Ajax request from “/friends/1.json”, simply do this:

<%= link_to "Awesome ajax link!", "/friends/1.json", remote: true, id: "ajax_link" %>

And that’s it! You have a Ajax link! It doesn’t do anything yet, but it will on the next step.

I added the “id” to the link so I can pick it easier with jQuery. But you don’t need to, if you want to make it another way.

Make a callback function

Ok, now the “difficult” part. When the response from the solicitation comes, you have to do something with it. But how do you know when the moment came?

You don’t. But the browser does. So tell the browser to call a function when the solicitation comes:

$(document).ready ->
    successCallback = (e, xhr, settings) ->
        myData = jQuery.parseJSON(xhr.responseText)
        # Do whatever you want here. Scramble your DOM, make an alert.
        # Everything you need is in the myData variable
    $('#ajax_link').bind("ajax:success", successCallback)

Ok. That’s not so difficult.

And this is not everything! You can make POST, PUT and DELETE via Ajax, too! Actually, you can do everything! And you do not need to change a lot of things on this tutorial, only how you’ll handle the data you are sending.

Don’t send Javascript as an Ajax response

In this post, I’ll assume that Rails’s asset pipeline was a good choice. This debate is irrelevant to this post. If you don’t like CoffeeScript, use Javascript.

I’ve read a lot of Ruby on Rails books, including Head First Rails, Ruby on Rails Up and Running, The Rails View, and also some Brazilian authors.

All of them made the same mistake, which brought me a lot of trouble: they teached that, in order to handle an ajax response, you have to make the requested controller send back a Javascript. Some of them even told that you should use “render :update” for it! I don’t know about other authors, maybe I’m simply unlucky.

Back at those times, my controllers were awful, filled with obscure code. So a lot of more experienced programmers told me that I could create a view, like “index.js.erb”, to generate the Javascript.

Something was still wrong. I thought to myself “but wouldn’t be a lot better if I requested some data and a callback function handled this data for me? Every Ajax book I’ve seen teaches me to do this! Why should it be so difficult with Rails?”

In fact, it’s not. It’s really easy. And it makes more sense.

Why would they pack Rails with CoffeeScript, if the controller would process a “js.erb”? You can and should handle the response with a CoffeeScript callback.

How to do that? Simple enough:

$(document).ready ->
    $("a#link_id").bind "ajax:complete", (e, xhr, settings) ->
        # TODO: the callback function goes here

This will go on app/assets/javascripts/<current page’s controller’s name>.js.coffee

You can put whatever you want to identify your link (or form) instead of “a#link_id”. Of course you can define the callback function outside of the bind and pass it as a parameter.

The content of the response is inside of xhr.responseText. For example, if you requested a JSON, you can do that:

response = jQuery.parseJSON(xhr.responseText)

And you’ll have all the data from the server.

There are also other Ajax events that may help your page to have a more responsive interface:





ajax:complete (it is after a success OR a failure, so don’t use it instead of ajax:success)

ajax:after (after the request is sent, not after the response was processed)

But why bother with this? Won’t a Javascript response work?

Well, there are a lot of situations where a Javascript response wouldn’t work. For instance, in this page (yes, it is an awful page, but it was only a concept test).

I needed each of these submit buttons to show my data in a different way. But the data I needed would be always the same. I could use three links and update them whenever the select changed, but this would not be practical at all. This was a lot simpler:

$("#report").bind "mousedown", ->
    $("form").bind("ajax:complete", reportCallback)

$("#graph").bind "mousedown", ->
    $("form").bind("ajax:complete", graphCallback)

$("#pizza").bind "mousedown", ->
    $("form").bind("ajax:complete", pizzaCallback)

There are situations where two different pages also need the same data, but they will also process them differently. A callback function would also be the best approach for it. As a general rule, getting data and processing it with a callback function will almost always be better.

For more information on the subject, I’d recommend you to read the excelent article from John Gadbois called Using Unobtrusive JavaScript and AJAX with Rails 3