Dehiwala, Sri Lanka
21-05-2010
Dehiwala, Sri Lanka
21-05-2010
Colombo, Sri Lanka
16-06-2010
Colombo, Sri Lanka
21-05-2010
Adding some AJAX to rails

by Sameera Gayan

OK, What is in for today? You might ask. I think as of now you are familiar with Ruby and Rails and are comfortable with writing-up a small Rails project like 'The Blog' as we did in earlier chapters.

So today I will show you a very interesting part of web programming and how easy its integrated with Rails.

Its AJAX. If you are into web development , you probably have heard of this term. AJAX stands for Asynchronous JavaScript and XML, :~< In simple words , its a method/technology where a web application can retrieve data from the sever in the background. The advantage is, application user will not know the difference as there will be no page refresh or such.

Let me give you an example. Say you have a profile update page. There you have one drop down for country and another for city. Ideally what you want to do here is, once the user selects a country, cities would be automatically filtered only for that country.

Now think about this scenario without AJAX. When user selects a country, you have to pass that country to the server and filter the cities. This is one trip to the server and since you are NOT using ajax your page will be re-loaded. In users view point its not very user friendly as the page reloads suddenly.

What is the AJAX solution, Scenario will be same and the approach will also be same. But the only difference is AJAX will be able to pass the country to the server, in the background and get the cities. Then user will not feel any difference.

So as always its very easy to do this with rails, lets see how.

First here is the scenario:

We have a page which has a text box, user types something in the text box. And when user clicks 'ok' button that should be shown below with out re-freshing the page

Lets do it

Create a rails project
rails AjaxTest

go to the project directory
cd AjaxTest/

Then create a controller called “main” (this will be our main page)
ruby script/generate controller main index

** note here, 'index' is our action
Set the home page
goto config/routes
change the following line
map.root :controller => "main"
Lets run the project

ruby script/server

Oops. Don’t forget to delete the public/index.html page

OK, now run the server ruby script/server

now its ok.

Lets add the text box and the button

go to app/views/main/index.html.erb

Change the code to this

<h1>Rails Ajax Test</h1>
 <p>Your Text<br/>
 <%= text_field 'custom', 'text' %>
 <input type="button" value="OK" onclick="ajax_function()">
</p>

 

So here we have added a text field and a button and in the buttons click event we have added an action. Wait.. you might ask, what is the difference, so far we have done the basic HTML and javascripts.

Let me show you, But before that , again back to some AJAX stuff, As I mentioned earlier AJAX technology and way of doing things. So there are many people who have written JavaScript libraries to get use of AJAX functionalities, and the good news is there are enough and more open source JavaScript frameworks which we can simply use.

And two leading libraries would be prototype (http://www.prototypejs.org) and jquery (http://jquery.com/) . Guess what? Rails has inbuilt support for prototype.

Lets get back to our project.

Add prototype javascript library to your page. In the head section. (in our case as we don’t have a layout you might need to change the view)

<html>
<head>
 <title>Your Text</title>
<%= javascript_include_tag :defaults %> </head>
<body>
<h1>Rails Ajax Test</h1>
 <p>Your Text<br/>
 <%= text_field 'custom', 'text' %>
 <input type="button" value="OK" onclick="ajax_function()">
</p>
</body>
</html>

Note the line <%= javascript_include_tag :defaults %> , this will add all the prototype libraries plus another JavaScript called 'application.js', which we can write our own methods

There we can implement our 'ajax_function()' of the button click

open up the public/javascripts/application.js

Add this function to the javascript

function ajax_function(){

}

Now lets add the content.

First we have to get the content of the text box. That would be
var text_box_value = document.getElementById('custom_text').value

and now we add a special code to make this AJAX working. Syntax of the code would be

new Ajax.Updater(<update element>,<server action>, {asynchronous:true, evalScripts:true, parameters:'<key>=' + <value>})

Let me elaborate on this one.

In this method, rails is basically using Ajax updater, which means rails will get a given content from the server and display it in the web page (inside a given section).

Note that this is a very high level method and calling the server + ajax part will be handled by rails and prototype

in above code

<update element> - where to show the new details
<server action> - what is the controller action to call
parameters – if we need to pass parameters we can use this

so to view this in action, lets create another method in our controller.

Do to app/controllers
add this method in main controller

def ajax_update
end

and remember we want to display the text that user types in the text box. We assume that we are receiving it as a parameter called 'input'

Let us modify our method a little

def ajax_update
  user_text = params[:user_text]
  @final_text = "You have entred #{user_text}"
end

and we need to create a view to display this text.
In app/views/main
create 'ajax_update.erb'
open it and add this code to display the text <%= @final_text%>

OK... lets get back to the 'application.js'

modify your function as follows

function ajax_function(){
var text_box_value = document.getElementById('custom_text').value
new Ajax.Updater('ajax_update_div','/main/ajax_update', {asynchronous:true, evalScripts:true, parameters:'user_text=' + text_box_value})
}

and remember to add a div in the app/views/main/index.html.erb

<div id="ajax_update_div"></div>

so final page would look like

<html>
<head>
 <title>Your Text</title>
<%= javascript_include_tag :defaults %> </head>
<body>
<h1>Rails Ajax Test</h1>
 <p>Your Text<br/>
 <%= text_field 'custom', 'text' %>
 <input type="button" value="OK" onclick="ajax_function()">
</p>
<div id="ajax_update_div"></div>
</body>
</html>

Now thats it... Lets check our ajax

run your server

type something in the text box
click ok.

Below you should see your new text without the need to refresh the page.

Easy.. isn’t it. This is only one way of doing ajax in rails, there are so many inbuilt easy ways to do this (thats for you to find out.) But here I wanted to show some inside also.

You can get the source in my git repo
git@github.com:sameera207/Rails-Lessons.git/source/rails_ajax

So until next month, happy programming!

Previous Article

Your rating: None Average: 5 (2 votes)

Post new comment

CAPTCHA
This question is for testing whether you are a human visitor and to prevent automated spam submissions.
Image CAPTCHA
Enter the characters shown in the image.