Monday, August 21, 2006

Ajax On Rails

Brief Introduction to Ajax and its Use:

Have you ever realize the fact that the Desktop applications that you use are much more responsive than the Web applications available on internet ? Of course you must have if you ever used a Web application. And the reason for the same is very obvious. In the Web applications, most of the time the client server communication happens involving the data to be posted to the server, processing the data at the server side, and then returning the result. Now when communication over network comes in picture, then the network latency also comes in picture. And this latency makes the Web application slow.

Now this is something which cannot be removed fully. But of course we can try to reduce it to the maximum extent we can. How?

The Answer is Ajax or Asynchronous JavaScript + XML. Here I am assuming that you people already know how Ajax exactly works so I am not going in detail. I would rather try to explain How is Rails and Ajax together are making a difference in the developing the real fast Web Applications. However if you would like to refresh the Ajax concepts a bit more before going ahead read this by Jesse James Garrett, who gave this technique a usable name: Ajax.

Implementing Ajax in your Web Application:

You can use Ajax in your Web application in various ways. One is to use the API of the XMLHttpRequest object directly in your own custom JavaScript. The main problem with this method is that you would need to deal with all compatibility issues of different browsers (which is the most hectic and pissing thing according to my own experience). The other way is to use various JavaScript libraries such as DWR, Prototype, Sajax, and Ajax.NET. The JavaScript libraries provide Ajax services and at the same time take care of the differences between various browsers. And the easiest way is to use the Ajax facilities of Ruby on Rails. Ruby on Rails offers you some powerful built-in Ajax features that makes using Ajax in your Web Application no extra burden anymore.

Pros and Cons of using Ajax in your web application:

Pros:

  1. Optimum use of Bandwidth: Since Ajax makes it possible to render a small portion of the page; therefore you can avoid displaying all the data at the same time by sending heavy request and getting heavy response each time a page loads. Instead, you can send smaller requests and refresh a smaller portion of the page. As the size of the requests (i.e. the data that is being transmitted and received over the network between the client and the server) reduces the bandwidth is also utilized properly.
  2. Responsiveness: Ajax uses DOM (Document Object Model) to manipulate the page currently displayed in your browser within the browser itself instead of creating the whole loop of sending each request to the server and receiving the response with all the unnecessary data that is finally going to be the same as it is in the current page. Thus the Web applications using Ajax become more responsive.

Cons:

  1. Unexpected "Back" button behavior: As the Ajax Web applications update the smaller portion of the web page, so if you trigger a few Ajax actions in a page, and expect to return to the previous page with the single Back button click then it might not be possible.

    Developers have implemented various solutions to this problem. These solutions can involve using invisible IFRAMEs to invoke changes that populate the history used by a browser's back button. Google Maps, for example, performs searches in an invisible IFRAME and then pulls results back into an element on the visible web page. Although the World Wide Web Consortium (W3C) has not formally deprecated the IFRAME element which was introduced in HTML 4, the standard recommends the OBJECT tag instead.
  2. Problem in Book-marking a page: Since the Ajax web pages are updated dynamically, it becomes difficult to book mark a state of the page.

Steps in which Rails implements the Ajax:

  1. A page containing some Ajax is loaded in the Browser.
  2. User triggers an Ajax activity in the Browser by clicking some button, modifying some data on the page, or clicking any link etc.
  3. The client sends the corresponding data required to be processed at the server side using XMLHttpRequest. This is done by the Ajax engine in between the client and the server. This data transmission is called Asynchronous data transmission because the data is actually not sent by the normal HttpRequest object, rather it is sent by the XMLHttpRequest object and through the Ajax Engine and not directly by your browser.
  4. The data received and processed at the server side by the corresponding action handler. The handlers generate and send back the response using XMLHttpResponse object. The response may be some HTML fragment, plain text etc.
  5. The Ajax engine receives the response on the client-side. The JavaScript that is required for this process is auto generated by Rails!! You need not write anything.
  6. A small portion of the user interface changes with the response. The portion that is updated or replaced in this action is mostly in a <div> tag.

Helper Methods to Implement Ajax in Rails:

Although Rails provides various helper methods that can be used to implement Ajax in the views of you web application, the most simple is the link_to() method. But before you can actually use the Ajax in your views of your web application, you need to activate the JavaScript. You need to include the following single line of code to activate the JavaScript for a view:

<%= javascript_include_tag :defaults %>

before the </head> tag.

Now suppose you have a web application that displays the list of the books that you have in your library, and one of the views in your application is there displaying the list of the books. You want to remove certain books that you know are outdated and are no longer in stock. Suppose you have a template called list.rhtml in the app/views/books directory which is displaying the list of the books you have. Now, to add a link to delete the books, you need to add the following lines of code in the list.rhtml template:

<%= link_to 'Destroy', {:action => 'destroy', :id => book}, :confirm => "Are you sure that the book is no more in stocks and you want to delete it?" %>;

The above code, adds an additional link besides show and edit (show and edit links become available just by scaffolding the books table) links in the lists of the books. On clicking the link, the JavaScript popup windows appear with the message that you have given in the "confirm" parameter. On clicking OK, as expected the corresponding book is deleted from the books database. There is another method similar to link_to() called link_to_remote(). This method differs in the number of parameters that it takes. In addition to the name of the link and the action parameter it also takes a DOM element ID. This element is the one the content of which you want to replace in the view after the corresponding action is performed. So, if you want to reload just the list of the books that you have in your library, instead of the whole page, you can replace the above line of code by the following:

<%= link_to_remote 'Destroy', {:action => 'destroy1', :id => list, :update => 'books'}, :confirm => "Are you sure that the book is no more in stocks and you want to delete it?" %>

Did you note the extra :update parameter ? The difference is now that on clicking the Destroy link now, the server will return an updated list of books. And this new list will be placed in the list DOM object which represents the list of books displayed on the page.

Note: The destroy1 action is yet undefined. So we need to define it in the app/controllers/books_controller.rb as follows:

def destroy1
Book.find(@params[:id]).destroy
render :partial => "books"
end


Let’s see what each does here: The first line deletes the book record from the database. The render method in the second line returns the response to the browser. The partial parameter of the render() method ensures that the webpage is reloaded partially. So here the updated list of the remaining books in the library is returned to the browser and is displayed without any need to reload the whole page.

So this is how the Rails uses the Ajax to build powerful and real fast web applications. Although there is much more to explore in this area and use in live applications for you, I would stop here only for now. I hope you people get motivated to some extent so that you start using it. I have already started. Looking forward to my reader’s comments and suggestions also. I would also be coming up with some more useful methods that you can use while using Ajax with Rails.

Till then "Happy Reading and Happy Programming :-) "

4 comments:

Anonymous said...

graet
keep me updated
i am lokking for a namk halal job withn rails in my future
i believ ur help will be crucial in it too
as off now i wil get through my degree in end of may 07
and i will search for a job in rails

looking for a job if u can help
plz do help me whho ever reads it

mail me@
mba.piyushgupta@gmail.com

Anonymous said...

Good day! 

How do you change the size of your monitor?

By the way, I love that too!  Where did you get that at?  

See you soon! Girly Girl 


how I make money with paid surveys

Anonymous said...

Good day! 

By the way, I love that too!  Where did you get that at?  

See you soon! Girly Girl 



see how I make free money with paid online surveys

Anonymous said...

retail job web site