Posts Tagged ‘ruby’

Create a Page Loading Animation Using Ruby on Rails and AJAX

Thursday, January 7th, 2010

I had a difficult time locating all the pieces needed to accomplish this so I’m pulling them together into one tutorial that will hopefully help more people out.

Purpose: I had a page in my Rails application which did a lot of processing before the page loaded. This could take up to a minute depending on how many items needed to be processed. Obviously, this made for a poor user experience. To correct this, I created a new page with an animated GIF and a short message explaining to the user that it could take some time to load. I then used AJAX to do the intensive processing and then overwrote the HTML in the DIV tag that displayed the animated GIF. I’ve outlined the steps I took below.

Step 1: Create Your Animated GIF

Go to to generate your animated wait image. Store the animaged GIF in your images folder.

Step 2: Add Remote_Function

You need to add the Rails remote_function code to create an AJAX call that runs when the page loads. To do this, you will need to add this code to the body tag.

<body onload="<%= remote_function(:url => { :action => :get_content_to_display } ) %>">

Step 3: Add Code to Display Animated GIF

Example: products/web_page.html.erb

<div id="display_ajax">
     <p>Please wait while your information loads.</p>
     <p><img src="/images/ajax-loader.gif" /></p>

Step 4: Create Partial to Display HTML Code

Example: products/_name-of-your-partial.html.erb

This file includes your display code.

Step 5: Create Controller to Display Ajax

Example: products_controller.rb

def get_content_to_display
     #Place code here
     render :update do |page|
          page.replace_html "display_ajax", :partial => 'name-of-your-partial'

Now when you load this page, the animated gif will run until Rails has completed your get_content_to_display action. When this done, page.replace_html will overwrite your animated GIF and display your new content.

If you have any questions, please email me, or post them in the comments below.