Create a Page Loading Animation Using Ruby on Rails and AJAX

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 www.ajaxload.info 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>
</div>

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'
     end
end

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, chris@marketingformavens.com or post them in the comments below.

Tags: , , , , , ,

View Comments to “Create a Page Loading Animation Using Ruby on Rails and AJAX”

  1. Ajax Libraries for Ruby on Rails…

    Ajax allows developers to build seamless refreshes on their web applications. By refreshing data without reloading the page, the technique can provide for a seamless user experience…….

  2. Fillev6 says:

    thx! searched a while on this

  3. Cafiah says:

    Hi!
    nice tutorial! i am searching for a loading animation for a while!

    anywayyy do you know a way to make it worked under rails 3?? cause remote_function doesn’t exist in rails 3?…

    Thanks!

  4. Kapil07517 says:

    good

Leave a Reply

blog comments powered by Disqus