Search code examples
ruby-on-railsajaxrjs

Why does my RJS stop working when I set options in form_remote_for?


I am running into a strange problem.
I simply want to display a loading icon on the page when pressing a button.
If my call to form_remote_for contains Ajax options then the RJS script does not work.

This works ("loading" is hidden by the controller and RJS):

View:

<%=form_remote_for(:job, @job, {:url => {:action=>:create}}) do |f| %>
[...]
<div id="loading">Loading...</div>

controller:

def create  
  render :action => "create.js.rjs"   
end

RJS:

page.hide 'loading'

This does not work (just adding :loading=> and loading is shown by the view but not hidden back by the controller as it was before):

<%=form_remote_for(:job, @job, {:url => {:action=>:create}}, {:loading=>"$('loading').show()"}) do |f| %>
[...]
<div id="loading" style="display:none;">Loading...</div>

So if my call to form_remote_for contains Ajax options then the RJS script does not work. Why?


Solution

  • Change your form to:

    <% form_remote_for (:job, @job, :url => {:action => :create}, :loading =>"$('loading').show()") do |f| %>
    # ...
    <% end %>
    

    Make sure create is:

      # POST /jobs
      # POST /jobs.xml
      def create
        render :action => "create.js.rjs"
      end
    

    And make sure your create.js.rjs is:

    page.hide 'loading'
    

    This scenario works for me. As you had it, it was returning the erb in the template because it was posting to "new" -- based on a quick scaffold implementation I did. Now I might still be missing something because as I said before the massive edit, I'm new, but this should get you going.

    EDIT: Removed "is this your code?" post.