views:

49

answers:

2

I am using remote form in Rails 3. It works fine but I want to show / hide spinner during ajax request.

In rails 2.3.* we use :before & :after in remote form to show/hide spinner

What should I do in Rails 3, as remote form of Rails 3 doesn't contain such options.

+1  A: 

I tried one solution & it worked

in view file :
<% form_for("", @search, :url => {:action => "search"}, :html => {:id => "search_form", :onSubmit => "$('search-loader').show();"}, :remote => true) do |f| %>

I used ":onSubmit" to show spinner & to hide it, I added one line in action "search" :
render :update do |page| ... page << "$('search-loader').hide();" end

It works great..!

rutvij pandya
A: 

Well, I'm using jQuery, and I'm doing the following, trying to be unobtrusive:

Add this, right before your </head> tag:

= yield :document_ready

Then in your application_helper.rb:

  def document_ready(content)
    html = %{ $(function(){#{content}})}
    content_for(:document_ready){ javascript_tag(html) }
  end

This allows you to load and run javascript once your document is loaded.

On top of the view containing your form add:

- document_ready("hide_button_show_spinner('your_button_id')")

In application.js

function hide_button_show_spinner(element_id) {
  $('#'+element_id).bind('click', function() {
    $('#'+element_id).after("<img src='/path/to/your/spinner.gif' class='ajax_loader' id='"+element_id+"_ajax_loader' style='display: none'/>")
    $('#'+element_id).hide();
    $('#'+element_id+'_ajax_loader').show();
  });
}

This will hide the button and show the spinner once the button is clicked. You may need to adapt this to your specific case. You can then show the button and hide the spinner in your javascript response (the .js.erb file that you render from the action called by the ajax request).

Yannis