Click to find out more about our Work
October 4th, 2008

Tutorial : Introduction to AJAX in Ruby on Rails with Prototype, Script.aculo.us

5 Comments

Heya,
After a long time I had the time to update my blog. I have been working on my project presentation for the past 2 weeks. The entire presentation was developed in Flash CS3 coded in ActionScript 3. It was ages since I had used Flash and I was quite astonished how it had changed over the years. I`ll be soon posting some tutorials on Flash, so do keep an eye out ;)

Anyways apart from being a bit off-topic, This tutorial deals with AJAX implementation in Ruby on Rails 2. While I was learning RoR, I had lot of issues of properly having AJAX implementation in my projects. This tuorial is for those people out there.

In this tutorial, I`ll just show some very simple Script.aculo.us Animation Implementations in RoR.
View Demo

Introduction

First off, if you followed my RoR tutorials, you should know that RoR has AJAX support built in to it. It uses the Prototype Javascript Library along with Scriptaculous.

Step 1 – Create new RoR Application

First create a new RoR application. Edit the database.yml file as well. If you are new to RoR, then visit Tutorial : Developing your First Ruby on Rails 2 Application

Step 2 – Create a Controller

After creating the new application, we need to create a controller. lets call the controller ajaxfunctions. I hope you guys know how to create a controller.

    ruby script/generate controller ajaxfunctions index

The above code will create a controller called ajaxfunctions which will have a method called index, respectively index.rhtml OR index.html.erb will be created inside the view/ajaxfunctions folder.

Step 3 – Editing the view file

Once you open it, you`ll notice that its empty. This is our template, basic HTML would suffice. So type out an html page here or you can use the one below.

<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
<title>Untitled Document</title>
</head>

<body>
</body>
</html>

Great. Now firstly, to implemenet AJAX in RoR , we need to initialize it.

Initializing the Ajax code

You must include the javascript code in your view template file (i.e index.rhtml in our case) for the Ajax functions to be available in that view. The best place for this is in the <head> tag.

You can either use

  • <%= javascript_include_tag :defaults %>
    We`ll be using this. Using this allows for quicker downloads since the script can be cached by the browsers.
    This is the output in the HTML page.

    <html>
    <head>
    ...
    <script src="/javascripts/prototype.js?1219423129" type="text/javascript"></script>
    <script src="/javascripts/effects.js?1219423129" type="text/javascript"></script>
    <script src="/javascripts/dragdrop.js?1219423129" type="text/javascript"></script>
    <script src="/javascripts/controls.js?1219423129" type="text/javascript"></script>
    <script src="/javascripts/application.js?1219423129" type="text/javascript"></script>
    ...
    </head>
    </html>
    
  • <%= define_javascript_functions %>
    This pastes all of the required Javascript code right into your view which increases your page size by ~20KB.

Different AJAX Helpers used in View Files

RoR creates the AJAX code for you via helper codes. Firstly

Defination:
What is a Helper ?
Helpers (“view helpers”) are modules that provide methods which are automatically usable in your view. They provide shortcuts to commonly used display code and a way for you to keep the programming out of your views. The purpose of a helper is to simplify the view. It’s best if the view file (RHTML/RXML) is short and sweet, so you can see the structure of the output. Nitty-gritty details are best left to helper methods and partials, where they can be parametrized and used repeatedly.

Note : We can call AJAX via 2 methods i.e 1) Using a button and 2) Normal Links. Then we can add the arguments through which we can achieve to have cool visual effects or perform serious AJAX operations.

AJAX Helpers

  1. button_to_function(button_value, *args, &mp;block)
    Returns a button that‘ll trigger a JavaScript function using the onclick handler. All of these go into the body tag of the view file. You can use the visual_effect function to specify any visual effects

    Example :
    This will show a button with the value “Greeting”, upon clicking will show a alert box with “Hello World!” inside.

    <%=button_to_function "Greeting", "alert('Hello world!')" %>

    This will display a button with value “Fade”, upon clicking will fade in or fade out the element ‘fade_text’ (It can be a div element with id=fade_text).

    <%=button_to_function "Fade", visual_effect(:toggle_appear, "fade_text", :duration => 0.5)%>
  2. link_to_function(name, *args, &block)
    Intead of a button, if you want to implement AJAX functionality using a text link. You can use this helper.
    Returns a link that will trigger a JavaScript function using the onclick handler and return false after the fact.

    Example :
    This will show a “Greeting” link, upon clicking will show a alert box with “Hello World!” inside.

    <%=link_to_function "Greeting", "alert('Hello world!')" %>

    This will display a “Slide Me” link, upon clicking it will slide in or out the element ‘slide_text’ (It can be a div element with id=slide_text).

    <%=link_to_function "Slide Me", visual_effect(:toggle_slide, "slide_text", :duration => 0.5)%>
  3. Helper for Animation

  4. visual_effect(name, element_id = false, js_options = {})
    Returns a JavaScript snippet to be used on the Ajax callbacks for starting visual effects.

    Example :
    This will show a “Highlight” button, upon clicking will highlight the element which is specified.

    <%=button_to_function "Highlight", visual_effect(:highlight, "element_id_name",:startcolor => '#ffff99', :endcolor => '#ffffff')%>

    This will display a “Grow” link, upon clicking it will grow the specified element_id_name

    <%= link_to_function "Grow", visual_effect(:grow,"element_id_name",:direction => "center",:duration => 1)%>

I would really suggest to go through Script.aculo.us WIKI to know more about every effect and their parameters. All of these effects can be used with RoR. For Example I have attached the code for the demo file.

Code for the Demo File

View Demo

<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
<title>AJAX</title>
<%= javascript_include_tag  :defaults %>
</head>

<body>

<%=button_to_function "Greeting Alert Me", "alert('Hello world!')" %><br /><br />
<h4>Actions with paragraph using buttons</h4>
<%=button_to_function "Fade", visual_effect(:toggle_appear, "fade", :duration => 0.5)%>
<%=button_to_function "Slide", visual_effect(:toggle_slide, "fade",:duration => 1)%>
<%=button_to_function "Highlight", visual_effect(:highlight, "fade",:startcolor => '#ffff99', :endcolor => '#ffffff')%>

<div id="fade" style="border:1px solid #dbdbdb; margin:50px;">
This is test, This is test<br>
This is testing....<br>
Lorum ipsum blablasadadada
</div>

<h4>Actions with Green Box using links</h4>
<%= link_to_function "Toggle Fade", visual_effect(:toggle_appear, "s1", :duration => 0.5)%> ||
<!-- Transitions --><%= link_to_function "Fade with wobble","new Effect.Fade('s1', { transition: Effect.Transitions.wobble })" %> ||
<!-- grow effect --><%= link_to_function "Grow", visual_effect(:grow,"s1",:direction => "center",:duration => 1)%> ||
<!-- shake effect --><%= link_to_function "Shake", visual_effect(:shake,"s1",:distance => "30",:duration => 1)%> ||
<!-- morph effect --><%= link_to_function "Morph to Red box", visual_effect(:morph,"s1",:style => "{background: '#f00',color: '#fff',width: '200px'}" )%> ||
<br>
<br>
<div id="s1" style="width:80px; height:80px; cursor:move; background:#88da5d; border:1px solid #444; text-align:center;">
</div>

<h4>Drag Action with Blue Box</h4>
<div id="s2" style="width:80px; height:80px; cursor:move; background:#7baaed; border:1px solid #333; text-align:center;">
<%= draggable_element("s2", :revert => true) %>
DRAG ME
</div>
</body>
</html>

Related Articles

Tutorial : Installing Ruby on Rails 2 in Windows Vista/XP
Tutorial : Developing your First Ruby on Rails 2 Application
Tutorial : Basics on Ruby on Rails 2 Model, Controller and Views and Routing
Tutorial : Create a blog using Ruby on Rails 2. (Part 1 – Relationships)
Tutorial : Create a login system in Ruby on Rails

This website uses IntenseDebate comments, but they are not currently loaded because either your browser doesn't support JavaScript, or they didn't load fast enough.

5 Responses to “Tutorial : Introduction to AJAX in Ruby on Rails with Prototype, Script.aculo.us”

  1. Cant see a demo
    July 21, 2009 at 5:22 pm

    Cant see a demo => Firefox can’t establish a connection to the server at http://www.visionmasterdesigns.com:12001.

    • Michael
      July 27, 2009 at 10:28 am

      Hey,
      since we have changed servers, we are having some trouble getting our Ruby On Rails demos up. We`ll notify as soon as it goes online

  2. PS
    June 20, 2009 at 5:58 pm

    @Plamen Nikolov: me either, where’s ajax there? Only some stuff to be interpreted by RoR and JS to fade divs. No interaction with server whatsoever.

  3. Plamen Nikolov
    March 9, 2009 at 6:05 pm

    I am sorry, but I cannot see any Ajax here, only Prototype and Scriptaculous

  4. autologo
    October 10, 2008 at 3:55 pm

    I have problem with AJAX, now I have not :)

Leave a Reply

XHTML: You can use these tags: <a href="" title=""> <abbr title=""> <acronym title=""> <b> <blockquote cite=""> <cite> <code lang=""> <del datetime=""> <em> <i> <p> <q cite=""> <strike> <strong>