views:

121

answers:

2

Hi,

I'm struggling to get my head around how to implement UJS in Rails (specifically, Rails 3 with jQuery). I've worked through Ryan's Railscast, and can follow what to do when submitting a form via AJAX, but I'm having trouble extending this concept to attaching a javascript function to a html element in my view files. Ultimately, I would like to be able to create a form where a different partial is rendered depending upon which radio button from a series is selected. Should I be looking at using the Prototype legacy helpers for this? And when do I need to create a .js.erb file?

Sorry for the newbie question, I've been unable to find much that explicitly outlines the concept of UJS and how to use it in a Rails app/switch over code from a RJS approach. Any help would be much appreciated!

+1  A: 

By using the remote => true on the form, your data will go to the server and all javascript returned will simply be executed, so here is a simple example:

<%= form_tag '/action_path', :remote => true do %>
  <%= radio_button_tag 'partial', 'one' %>
  <%= radio_button_tag 'partial', 'two' %>
  <%= submit_tag 'select' %>
<% end %>

<div id="partial_holder">

</div>

On the server

def action
  #do whatever you want with parameters
end

On the action.js.erb file

$('#partial_holder').html(<%= escape_javascript(render(:partial => params[:partial])) %>)
Angelus
Thanks for the response - trouble is, I don't want the form submission itself to be AJAXy, just the elements within the form...
Sonia
If only parts of the form will be AJAX sent, you'll have to either make more than one form or simply make custom javascript to send requests with your elements inside the form. It's a bit hard to understand exactly what you want to do without any kind of code or example :/
Angelus
From what I've read it seems like Rails 3 requires developers to write more of their own javascript by removing a lot of helper methods, so thanks for the comment about the custom javascript - I'm just going to have to brush up on my js skills a bit!
Sonia