If you're new here, you may want to subscribe to my RSS feed. So that you can read the latest updates about Web2.0 tools, Making Money Online, Tips in SEO, Ajax and many more. Thanks for visiting ProgramimiCOM!

Java and Flash offer real alternatives for those trying to build web applications that function more like desktop applications. However, they have their shortcomings. AJAX overcomes these shortcomings — especially if you use Ruby on Rails.

Interactivity and responsiveness has been considered the USP of desktop applications and not of web applications. Even though there exist mechanisms such as Java Applets and Flash files that provide interactivity and responsiveness up to a point, they are intrusive. That is, the user needs to install either a Java or a Flash plug-in.

However, with AJAX coming into the foreground, a non-intrusive way of providing interactive and responsive web applications has evolved. Even with AJAX, the problem is not fully solved for developers. The reason for this is the peripheral integration of AJAX in almost all the existing frameworks. Still, there are exceptions in the form of frameworks that provide AJAX-based functionalities as their core services. Ruby-on-Rails (RoR) is one of them.

In this discussion, I will be focusing on using AJAX with RoR. The first section will be a brief overview of AJAX. In the second section, I will detail the steps involved in AJAXifying the RoR application. In the last section, I will be developing a real world application using AJAX and RoR. That’s the agenda for this discussion.

AJAX: an Overview

By definition AJAX is “a technique that extends the traditional web application model to allow for in-page server requests.” In other words, AJAX provides the functionality to make on the fly requests to the server and present the response data to the user by modifying a part of the page without refreshing the whole page. AJAX is not a single technology; rather, it’s a combination of technologies. These technologies form the basic components of AJAX, which are:

  1. JavaScript
  2. XMLHttpRequest
  3. XML

The second component is an object of JavaScript itself. However the first ‘A’ of AJAX comes from it. The reason for this is detailed below.

JavaScript is the “J” in AJAX. It is the JavaScript that parses the response from the server and makes appropriate changes to the current page. Using JavaScript, one can change a paragraph, replace a product image or change the complete look and feel of the page without the intervention of the server. This reduces the bandwidth and makes the web site look more responsive to the user.

XMLHttpRequest is an object of JavaScript that not only allows the user to create or construct HTTP calls from within the script but also process the response sent by the server. It is available as an ActiveX control in Internet Explorer and as a JavaScript object in other browsers. Though it is known as XMLHttpRequest, one can wrap any kind of HTTP communication using it.

The first ‘A’ in AJAX, which stands for “Asynchronous,” comes at the “behest” of XMLHttpRequest. One of the abilities of XMLHttpRequest is to make a call to the web server in the background while the user continues to do his/her work on the UI. Whenever the response is received, the XMLHttpRequest accepts it and passes it over to the function that is registered to handle the response. Thus the request-response cycle is relieved off the paradigm of synchronous communication.

If one looks up the definition of XML on the net, the most common definition found is this: “XML (Extensible Markup Language) is a W3C initiative that allows information and services to be encoded with meaningful structure and semantics that computers and humans can understand and is great for information exchange, and can easily be extended to include user-specified and industry-specified tags.” The extensibility and the ability to provide data in a structured format is the main reason for XML to be the preferred response data format sent by the server. This doesn’t mean that the server can’t send data in any other format. It can send data in any format and XMLHttpRequest can accept and process it. However, since XML is a standard that is both extensible and structured, it is preferred over every other.

The next obvious question is how these three components fit in the overall picture. Here is an example of AJAX at work. It checks the validity of the username.

var xmlHttp;
function createXmlHttpRequest()
{
//check the type of browser and initialize XMLHttpRequest object
if(window.ActiveXObject)
{
xmlHttp=new ActiveXObject(”Microsoft.XMLHTTP”);
}
else if(window.XMLHttpRequest)
{
xmlHttp=new XMLHttpRequest();
//alert(”inside elseif…”+xmlHttp);
}
}

//This method creates an instance of XMLHttpRequest and calls the server
//Then delegates the data processing to another function on receipt of data
function startRequest()
{
createXmlHttpRequest();

var u1=document.f1.user.value;
xmlHttp.open(”GET”,”validate.php?user=”+u1,true)
xmlHttp.onreadystatechange=handleStateChange;
xmlHttp.send(null);
}

//Does the handling of data and presentation of data
function handleStateChange()
{
if(xmlHttp.readyState==4)
{
if(xmlHttp.status==200)
{
document.getElementById(”results”).innerHTML= xmlHttp.responseText;
}
else
{
alert(”Error loading pagen”+ xmlHttp.status +”:”+ xmlHttp.statusText);
}
}
}

function resetDisplay()
{
document.getElementById(”results”).innerHTML=” ”

}

The logic here is very simple, yet the amount of boilerplate code required is pretty high and the complexity of JavaScript increases with the increase in complexity of the logic of data processing and presentation. And I have not shown the logic at server-side. This is the story with almost all of the technology except Ruby-on-Rails. How RoR is different from the others is the topic of the next section.

Implementing AJAX

In the last section, the example demonstrated the complexity involved in AJAXifying an application having even the simplest logic to be implemented. So how can RoR make it simple? RoR does it by providing AJAX as one of its core functionalities. RoR has the prototype, effects, dragdrop and controls JavaScript libraries as built-in libraries. Secondly, a helper called JavaScriptHelper provides wrapping around JavaScript code so that switching between Ruby and JavaScript won’t be necessary. So RoR makes things simpler by wrapping JavaScript libraries and providing them as built-in RoR libraries.

Now let’s look at ways to use AJAX within RoR. To implement AJAX, RoR provides two basic ways which are:

  1. Using link_to_remote()
  2. Calling form_remote_tag()

The former is used with non-form HTML whereas the later is used with form and form based HTML elements.

The link_to_remote() is one of the simplest yet versatile and flexible helpers in RoR. It takes following parameters:

  1. the text for the link
  2. the id of the link
  3. the URL of the action to be called when the link is clicked
  4. the position which tells Rails to insert the response instead of replacing the existing content. This is an optional parameter used with the advanced form of link_to_remote().

So what are the steps required to use link_to_remote()? The steps are as follows:

  1. Create the page to be shown to the user
  2. Implement the controller to be called by link_to_remote()
  3. Develop the page that will provide the response

The steps are common to that of any typical RoR. That is the beauty of RoR. Of these steps, the third step is optional if rendering is taken care of by the action itself.

  1. Create the page to be shown to the user:This step involves creation of an RHTML template with the addition of link_to_remote(). However, to call it, another helper will have to be included - javascript_include_tag. Using this one can include any of the four JavaScript libraries. For calling link_to_remote() we need the prototype library. So the statement would look like this:

    <%= javascript_include_tag “prototype” %>

    Here is an example of a page having link_to_remote():

    <html>
    <head>
    <title>Ajax Demo</title>
    <%= javascript_include_tag “prototype” %>
    </head>
    <body>
    <h1>What time is it?</h1>
    <div id=”time_div”>
    I don’t have the time, but
    <%= link_to_remote( “click here”,
    :update => “time_div”,
    :url =>{ :action => :say_when }) %>
    and I will look it up.
    </div>
    </body>
    </html>

    The link_to_remote() is passed three arguments: the text to be shown i.e. “click here”, the id of the link created which is “time_div” and the action to be called which is say_when. The next step is to implement the controller containing the action.

  2. Implement the controller to be called by link_to_remote()The action within the controller can be implemented in two ways. The first way involves a simple action which in turn calls the corresponding RHTML, while the second way renders the response using render_text. The following is an example of the first type:

    class DemoController < ApplicationController
    def index
    end

    def say_when

    render(:layout => false)

    end
    end

    The render function is called with the layout option as false because only a part of the HTML page is being updated; hence there is no requirement of any Rails layout wrappers. The example of the second type is as follows:

    class DemoController < ApplicationController
    def index
    end

    def say_when
    render_text “<p>The time is <b>” + DateTime.now.to_s + “</b></p>”
    end
    end

    It uses render_text method to generate the response.

  3. Develop the page that would provide the response:This step is required only in case of an action that calls view to generate a response. The view corresponding to the action is again a straight forward RHTML:

    <p>The time is <b> <%=DateTime.now.to_s%>

    </b></p>

    That’s how link_to_remote() is used. Next let’s see how form_remote_tag() is used.

While dealing with links, link_to_remote() is handy but what about form elements? That’s where form_remote_tag() comes in. One can easily enable any Rails form to use AJAX using form_remote_tag(). It serializes and sends all the form elements to the server via XMLHttpRequest. All this is done automatically without any requirement for extra logic implementation. The form_remote_tag() takes three parameters:

  1. The update parameter specifies the id of the element that needs to be updated using the response of the executed action.
  2. The url parameter specifies the server-side action to call.
  3. The position parameter tells Rails the position in which to place the response data.

To use the form_remote_tag() there are three steps:

  1. Create the page to be shown to the user.
  2. Implement the controller to be called by form_remote_tag().
  3. Develop the page that will provide the response.

The steps are similar to those of using link_to_remote(). Only the way they are implemented is different.

  1. Create the page to be shown to the user:The main change from the page for link_to_remote() is that form_remote_tag() uses form elements. Hence the page also contains form elements instead of links. A simple page using form_remote_tag() would look as follows:

    <html>
    <head>
    <title>Ajax List Demo</title>
    <%= javascript_include_tag “prototype” %>
    </head>
    <body>
    <h3>Add to list using Ajax</h3>
    <%= form_remote_tag(:update => “my_list”,
    :url => { :action => :add_item },
    :position => “top” ) %>
    New item text:
    <%= text_field_tag :newitem %>
    <%= submit_tag “Add item with Ajax” %>
    <%= end_form_tag %>
    <ul id=”my_list”>
    <li>Original item… please add more!</li>
    </ul>
    </body>
    </html>

    Here the id of the element is given as my_list which is the id of the list that will be populated by the response provided by the action. The url specifies the action to be called and the position tells Rails to place the returned HTML snippet on the top of the element whose id has been specified in the update parameter. Now let’s look at the action.

  2. Implement the controller to be called by form_remote_tag():Just as in the case of link_to_remote() helper, the action can either render the response directly using render_text or else it can delegate it to another RHTML. If render_text is to be used the code would be:

    class ListdemoController < ApplicationController
    def index
    end

    def add_item
    render_text “<li>” + params[:newitem] + “</li>”
    end
    end

    whereas if the rendering is to be done by a template then the code would be:

    class ListdemoController < ApplicationController
    def index
    end

    def add_item
    @item= params[:newitem]
    render(:layout => false)
    end
    end

    The only difference is that the parameter passed by form_remote_tag() is placed in a variable called item which can be used in the template.

  3. Develop the page that will provide the response:The add_item.rhtml would be like:

    <li> <%=@item%> </li>
    That’s it.

    So now you have seen how easy the steps are for creating an AJAX based application in RoR. Next I will develop a real world application using RoR and AJAX.

Ruby-on-Rails and AJAX

In real world applications one of the most required functionalities is to populate a combo box based on the data entered in a preceding field such as a text box or another combo box. In this example, I will be developing such a part for an application. This can be used with any application with slight modifications. It contains two components:

index.rhtml - the view which contains the combo box to be filled and the
combo box on the basis of which the filling has to be done

PopulateController - the controller containing the action required for the
populating of the combo box.

Here is the index.rhtml:

<html>
<head>
<meta http-equiv=”content-type” content=”text/html; charset=utf-8″ />
<%= javascript_include_tag “prototype” %>
<title>Ajax Rails & Select lists</title>
</head>
<body>
<%= form_remote_tag(:update => “sel_con”,:url => {
:action => :create_select },
:position => “top”,:success => “$(’sel_con’).innerHTML=”” ) %>
<p>
Please select a sports category:
</p>
<p>
<%= select_tag “categories”,
“<option>Team</option><option>Individual</option>” %>
</p>
<div id=”sel_con”></div>
<p>
<%= submit_tag “Show Sports” %>
</p>
<%= end_form_tag %>
</body>
</html>

The combo box contains two values, team and individual. Based on the selection the second combo has to be populated and shown at the div having the id sel_con. If team is selected by the user, the second combo box would be filled with team events whereas in the case of individual, individual event is populated. The form_remote_tag is passed four parameters: the id of element to be updated, the action to be called, the position in which to place the result and what has to be done if the request is successfully executed. In this case the inner HTML is set to no value i.e. “”. Next is the controller:

class PopulateController < ApplicationController
def index
end

def create_select

indArr=[”Nordic Skiing”, “Inline Skating”,”Tennis”,
“Triathlon”,”Road Racing”,”Figure Skating”,
“Weight Lifting”,”Speed Skating”,”Snowboarding”];
teamArr=[”Soccer”,”Basketball”,”Football”,”Hockey”,
“Baseball”,”Lacrosse”];
str=”";

if params[:categories].index(’Team’) != nil
render :partial => “options”,
:locals => { :sports => teamArr,:sptype => “team”}
elsif params[:categories].index(’Individual’) != nil
render :partial => “options”,
:locals => { :sports => indArr, :sptype => “individual” }
else
str=”<select id=’individual’ name=’individual’>
<option>unknown</option></select>”;
render :text => str;
end

#end method
end
#end class definition
end

The create_select is the action where the logic for creating and populating the second combo box goes. First it creates two arrays with team and individual sports events. Then based on the parameter received, the combo box is created and populated. This is done in the statement

render :partial => “options”,
:locals => { :sports => teamArr,:sptype => “team”}

Now let’s look at _options.rhtml which is a partial template i.e. the a piece of HTML code that can be used again and again. Here is the code:

<select id=”<%= sptype %>” name=”<%= sptype %>”>
<% sports.each do |sport| %>
<option><%= sport %></option>
<% end %>
</select>

It first gives the combo box an id, iterates through the array passed and populates the combo box. That’s it. This completes the application. Though I had mentioned four libraries, I have introduced only one of them. In the next discussion, I will be focusing on UI using the other three libraries. Till then..

by A.P.Rajshekhar