Topic: AJAX Submit for radio_button_tag in Rails 3

I have a questionnaire with list of questions with radio buttons (1..5), what i'd like to do is submit the form to the database once a user clicks on an answer for any question.  At the end I have a save button, which will also submit to the DB, but show some validation.  Below is the code:  <table> <%= form_tag complete_interviews_path, :method => :put do %>   <tr>     <td> <%= radio_button_tag

Re: AJAX Submit for radio_button_tag in Rails 3

Your post got truncated....

I'm confused you want to submit a question when a user clicks on a radio button, yet you have a save button below that seems to do the same thing? Why do you want to submit the question and answer when they click on a radio but, seems like you should give them breathing room if they decide to change there answer.

Also, what validations are there if the only option a user has is radio buttons, seems like they can't mess that up?

However, with jQuery, you could do something like this:

$(function(){
   $('table#yourtable tr > td:radio').click(function(){
     $.ajax({url: "/path_to_your_controller_action"    // etc... (docs.jquery.com)
   });
});
- Ben

Re: AJAX Submit for radio_button_tag in Rails 3

Thanks for the reply.  Basically I need to save the answer to the DB once they click a radio button, because I need to validation against a certain distribution of answers.  This way I can have a link on the page called "View Distribution" which will show a graph of their current distribution, but this is of no use if the answers have not been saved.

If they click the save button at the end then they will get validation errors if they have the wrong answer distributions.

Re: AJAX Submit for radio_button_tag in Rails 3

Ok, in that case, you're going to need some javascript and I would HIGHLY recommend this be ajax because it would be a bad user experience to be filling out a bunch of questions and everytime they click a radio but the page has to reload.

I'd recommend jQuery (it's what I know and very popular, as well as pretty easy for standard stuff)

We could do something like this (It's the javascript jquery representation of observe_field and observe_form):

<!-- HTML code -->

<table id="yourTable">
  <%= form_tag complete_interviews_path, :method => :put do %> 
    <tr class="radio">
      <td> <%= radio_button_tag('name', 'value', false) %> </td> <!-- see the false, that means the radio button isn't selected -->
    </tr>
   <% end %>
</table>
// JS code

jQuery(function($) {

  // Select all radio buttons and bind the .change handler on them, so if their value changes (their value is false
  // as described in the embedded ruby code above, where I put "false" in the radio button form field element) run the
  // following code

  // note the change i just made =>   tr.radio > td input:radio, it has to be input:radio, not td:radio
  // this selects all table rows with a class radio, then it selects their child (>) td elements that contain input fields with type radio (input:radio)

  $("tr.radio > td input:radio").change(function() {
    var data = $(this).attr("value"); //store the value of the radio button in variable called data

    // make a POST call and if there is a response, do something with that response (i.e. put it in a div on the page or something)
    $.post('/questionaire/your_action', {'data': data } function(data) {   // post to the url, then send params labeled 'data' and pass it the variable data, then have a function that intercepts the data passed back to it (if you are going to pass something back to it)
      $("div#results").html(data); //place data in a div somewhere, or not if you don't want to
    });
  });
});
# Controller code, questionaire controller

def your_action
  data = params[:data]
  data.save
  #something like this
end

Something similar to this should do it

Last edited by RailsRhino (2010-11-20 21:01:57)

- Ben

Re: AJAX Submit for radio_button_tag in Rails 3

Thanks again, tried the code but for some reason can't get the java script to fire off when I click on a radio button.  I made sure to set to false if not selected.  Any ideas?  Do you have a working example that I maybe able to take a look at?  Also is this easy to do using prototype? 

Thanks

Re: AJAX Submit for radio_button_tag in Rails 3

I don't really know prototype, but there is a way to do it with prototype, i jsut can't help you there.

However, I'm trying to get exactly what you're doing working on my computer right now just because I thought it would be a good exercise for me to do it. If I come up with something, I'll be sure to send it to you.

- Ben

Re: AJAX Submit for radio_button_tag in Rails 3

In the mean time, you can do this code to make sure you're grabbing the appropriate value from the radio buttons:

<form name="form" action="" id="form1">
    <table>
      <tr class="radio">
        <td><input id="gender_male" name="gender" type="radio" value="male" /></td>
        <td><input id="gender_female" name="g" type="radio" value="female" /></td>
        <td><input id="gender_m" name="ge" type="radio" value="m" /></td>
        <td><input id="gender_f" name="gen" type="radio" value="f" /></td>
      </tr>
    </table>
    
  </form>
  
  <script type="text/javascript">
    $(function(){
      $("tr.radio > td input:radio").change(function() {
        var data = $(this).attr("value"); 
        alert(data);
      });
    });
     
  </script>
- Ben

Re: AJAX Submit for radio_button_tag in Rails 3

OHHHH wait.. I forgot to tell you, if you're using jQuery, there are a few things you must change.

First: grab the jQuery library, you can download it at jquery.com

Second: you need to delete all the javascript libraries out of your javascripts folder except application.js, then put the jquery library you just downloaded in this folder.

third: you need to get the jquery version of rails.js, found here. ... it'll look like this: rails-jquery-ujs-ff185db , but inside it it contains "rails.js" (in the "src" folder) and that's what you need to put into your public/javascripts directory.

If you downloaded the latest version of jQuery, which is what is on the home page of their site, 1.4.4, then make sure you get the latest version of rails.js at github. If you're using jquery v.1.4.2 or less, you have to download the older version of rails.js at github. It doesn't matter whether you use 1.4.2 or less, or 1.4.3 or higher, either are going to have same results for your application. Just make sure rails.js and your jquery library versions are in sync with one another. Once you get rails.js (when you download from github, it'll be in a folder with some other stuff. Go into the source directory and you'll see rails.js) add rails.js to your public/javascripts directory with jQuery.js and application.js.

fourth: go into config/application.rb and add this line of code under class Application < Rails::Application

class Application < Rails::Application   #### this line is already there
  
config.action_view.javascript_expansions[:defaults] = %w(jquery.min rails) 
#### this ^ is the line to add, right below class Application < Rails::Application, like I have here

then once you have done that, go to your layout file: application.html.erb in app/views/layouts

change the javascript_include_tag to this:

  <%= javascript_include_tag "jquery.js", "rails.js", "application.js" %>

Once you have done those steps, you're all set for jQuery. To test, the last post I wrote showed you how to grab those radio button values, to make sure jquery is working, copy and paste all that code into a view and give it a shot. It should most definitely work if you completed the steps above.

I knwo this sounds like a lot, but A LOT of people these days are using jQuery and it's really awesome, you should use it. Railscasts often uses jquery, and that's the source for a TON of knowledge for most people, you'll likely come across it soon if you haven't already.

Besides, once you do this once, you can save a rails app as a template with all this already done. Then each time you want to make a new app, you just copy your template app and rename it, takes less time than generating a new app!

Last edited by RailsRhino (2010-11-20 22:05:10)

- Ben

Re: AJAX Submit for radio_button_tag in Rails 3

Ohh and is there a reason you're using tables for the HTML, this is something that seems like it should be a unordered list?

- Ben

Re: AJAX Submit for radio_button_tag in Rails 3

I hacked up the example I provided, I'll email it to you

- Ben