ruby-on-railslink-to-remote

How do I use link_to_remote with a form as the remote URL?


I want to render a form (fields and includes a submit button) when using link_to_remote -- the form appears via an ajax call.

I'd like that form to behave as any other form would (it's a basic New Active Record) form, nothing fancy.

Upon submit, though, I'd like the original parent page to remain static without refreshing and, instead of the form, the notice (your form has been successfully submitted) in its place.

Current behavior, upon submit, it redirects the entire page.

I put the remote into a method:

<%= do_event_remote(contact_event, event) %>

And here is this helper method:

  def do_event_remote(contact, call_or_email_or_letter) 
    model_name = call_or_email_or_letter.class.name.tableize.singularize 
    link_to_remote "#{model_name.camelize}", 
                   :url => send("new_contact_#{model_name}_path", 
                                            :contact => contact, 
                                            :status => 'done',
                                            :"#{model_name}" => call_or_email_or_letter ),
                   :update => 'remote_event'                                     
  end 

Thanks...


Solution

  • You create the form as normal but you use the remote_form_for helper in the place of the form_for and the remote_form_tag in the place of form_tag. This will submit the form via ajax.

    Documenation at: http://api.rubyonrails.org/classes/ActionView/Helpers/PrototypeHelper.html

    Update: Example:

    In your form (using haml):

    = remote_form_for @customer, :url => customer_path(@customer), :complete => "doSomething(request)" do |f|
      %p
        First Name<br>
        = f.text_field :first_name
      %p
        Last Name<br>
        = f.text_field :last_name
      = submit_tag "Update"
    

    For your fade functions, you would need to use scriptaculous or jquery. Scriptaculous comes packaged with rails and is currently the default. For that, your javascript would be something like this:

    function doSomething(request){
      Effect.fade('some_div');
    }
    

    more on scriptaculous: http://wiki.github.com/madrobby/scriptaculous/