Rails Magic with Ajax

Without using any framework, it used to be a lot of lines (probably 50 lines) just to setup a AJAX connection. Adding the actual request, server handling and callback functions, it will end up another 10 or 20 lines per request. All added up to around 60 – 70 lines of codes at least for 1 request.

With jQuery, we can skip the connection setup part because it’s already included inside the framework. After that, you can construct the request just in 1 line of code together with the callback function. But the server handling is still up to you which is normally 5 – 20 lines depending on the language and the task. So, it’s about 20 lines in total.

Now, with rails, you can end up to less than 5 lines of codes. 1 (3 words to be exact) to AJAXify a request.

:remote => true

Just add these three words to your link_to or button_to methods and it will create the request already.

button_to 'add item', :item, :method => post ,:remote => true

Next, another 1 line to remind the server to treat it as an AJAX request by using


Add this into the corresponding controller action, in the response_to method call

respond_to do |format|
  format.html { redirect_to(store_url) }
  format.xml  { head :ok }

And lasty, you need to create the callback which is normally in javascript. First you need to create a js.rjs file in your views folder and name it as the action name. For example, if it’s for a create action, you will create a create.js.rjs file. Put the callback function in this file and you have a AJAX application running on your Rails.

Magic #2

We already saved up typing around 50 lines of codes for this. But Rails actually do more than our previous 60 lines of codes. It also handle the noscript for you. Which might end up creating another 10 or 20 lines of codes without Rails. noscript is codes or behaviors that happen when the user turn of javascript. So, if we don’t handle this situation, the whole application will just failed because AJAX is depending fully on Javascript.

So, just by writing around 5 lines of codes, we get :

1. Ajax request with callback and server handling.

2. noscript handling, which will works perfectly fine without javascript turned on.


Leave a Reply

Fill in your details below or click an icon to log in: Logo

You are commenting using your account. Log Out /  Change )

Twitter picture

You are commenting using your Twitter account. Log Out /  Change )

Facebook photo

You are commenting using your Facebook account. Log Out /  Change )

Connecting to %s