Programming Tutorials Browser Tutorials Articles Struts Tutorials Hibernate Tutorials

  Tutorial: Ajax on Rails

This article introduces the incredibly easy-to-use Ajax support that is part of the Ruby on Rails web application framework.

Tutorial Details:

How to Use Ajax in Your Web Application
The hard way to use Ajax in your web app is to write your own custom JavaScript that directly uses the XMLHttpRequest object's API. By doing this, you have to deal with the idiosyncrasies of each browser.

An easier way is to use one of several JavaScript libraries that provide higher-level Ajax services and hide the differences between browsers. Libraries such as DWR, Prototype, Sajax, and Ajax.NET are all good choices.

The easiest way of all is to use the built-in Ajax facilities of Ruby on Rails. In fact, Rails makes Ajax so easy that for typical cases it's no harder to use Ajax than it is not to!

How Rails Implements Ajax
Rails has a simple, consistent model for how it implements Ajax operations.

Once the browser has rendered and displayed the initial web page, different user actions cause it to display a new web page (like any traditional web app) or trigger an Ajax operation:

A trigger action occurs. This could be the user clicking on a button or link, the user making changes to the data on a form or in a field, or just a periodic trigger (based on a timer).
Data associated with the trigger (a field or an entire form) is sent asynchronously to an action handler on the server via XMLHttpRequest.
The server-side action handler takes some action (that's why it is an action handler) based on the data, and returns an HTML fragment as its response.
The client-side JavaScript (created automatically by Rails) receives the HTML fragment and uses it to update a specified part of the current page's HTML, often the content of a
tag.
An Ajax request to the server can also return any arbitrary data, but I'll talk only about HTML fragments. The real beauty is how easy Rails makes it to implement all of this in your web application.

Using link_to_remote
Rails has several helper methods for implementing Ajax in your view's templates. One of the simplest yet very versatile methods is link_to_remote(). Consider a simple web page that asks for the time and has a link on which the user clicks to obtain the current time. The app uses Ajax via link_to_remote() to retrieve the time and display it on the web page.


 

Read Tutorial at: Click here to view the tutorial

Rate Tutorial:
Ajax on Rails

View Tutorial:
Ajax on Rails

Related Tutorials:

Site navigation
 

 

Send your comments, Suggestions or Queries regarding this site at roseindia_net@yahoo.com.

Copyright © 2006. All rights reserved.