Rubytastic
Rubytastic

Reputation: 15501

How can I submit a Rails form with AJAX but also trigger a jQuery action?

I'm trying to submit a Rails form with AJAX.

I have some toggle on/off jQuery function that sets some color to green and red, if someone likes or dislikes.

What I'm trying is to have it call my jQuery function to toggle the color and then submit the form with ajax to a rails function with the status of like/dislike submitted.

My form:

#wrapper_select.like_select
    =  form_for @paintings, :url => "/paintings/handlelike", :method => "post", :remote => true, :html => {:name => 'form'} do |f|

      = hidden_field_tag :s_id, params[:id]
      = hidden_field_tag :likes, params[:choice]

jQuery function:

$('.like_select').click(function () {
    if (this.className.match(/like_yes|like_no/)) $(this).toggleClass('like_yes like_no');
    else  $(this).toggleClass('like_yes');

  })

How can I call the toggle js function (the function works okay by itself) and submit with ajax the form and then the value if a user likes/dislikes?

Upvotes: 0

Views: 1480

Answers (2)

Muhammad Sannan Khalid
Muhammad Sannan Khalid

Reputation: 3137

Use ajaxsubmit function from jquey.form plugin there you can call another function. here is a link to jquery.form plugin.

http://jquery.malsup.com/form/

___________EDIT 2_____________

= javascript_include_tag "jquery.form", "jquery.validate", "attachment_validation"
=  form_for @paintings, :url => "/paintings/handlelike", :method => "post", :remote => true, :html => {:id => "submit_form_id",:onsubmit => "return false;", :name => 'form'} do |f|


  = submit_tag "submit", :class => "ClickClose", :id => "submit_form_btn"

your js

$("#submit_form_btn").click(function() {
    //call your second function before submitting

          $('#submit_form_id').submit(function() {
            $(this).unbind('submit').ajaxSubmit({
              success: function(data) {
                //do something on success case.
              }
            })
            return false
          });
  });

Upvotes: 1

allenhwkim
allenhwkim

Reputation: 27748

Submitting a form with Jquery ajax requires extra stuff to handle.

  1. form validation
  2. collect values and submit it with Jquery POST
  3. Processing response and display message

Better to see it. this is a good example i think

http://net.tutsplus.com/tutorials/javascript-ajax/submit-a-form-without-page-refresh-using-jquery/

Upvotes: 1

Related Questions