Hugs
Hugs

Reputation: 935

Submit Rails form using jQuery

I am trying to submit a Rails form using jQuery and Ajax however it is not working and I am not sure why. I realize there is the remote: true to do things using AJAX but this is not enough in my case as I want to perform other jQuery actions when the submit buttons is clicked and give good feedback on the status of the action i.e success and failure. This is code I currently have the form:

<%= form_for @mail, id: "mail-form", url: subscription_mail_create_recipients_path(@mail) do |f| %>

    <strong>Choose the users you want to target..</strong><br/>

    <%= f.check_box :target_users %> Users                          

    <div class="actions">
    <a id="save-config" class="btn btn-primary purple-button">Save configuration</a>
    </div>
<% end %>

The jQuery:

    $('#save-config').click(function(){
        $('#mail-form').submit(function() {
            var valuesToSubmit = $(this).serialize();
            console.log(valueToSubmit);
                            $.ajax({
                                url: $(this).attr('action'), //sumbits it to the given url of the form
                                data: valuesToSubmit,
                                dataType: "JSON" // you want a difference between normal and ajax-calls, and json is standard
                            }).success(function(json){
                                //act on result.
                            });
            alert("method failed");
                            return false; // prevents normal behaviour
        });
    });

I am trying to work off the example here Submit form in rails 3 in an ajax way (with jQuery)

I have no submit button, is that the reason it is not working? Any help would be appreciated thanks.

Upvotes: 3

Views: 4434

Answers (1)

krichard
krichard

Reputation: 3694

Your code does define function to be executed when the form is submitted. it does this for every click on your button. But what you want is to submit the contents of the form for every click. So try the following:

$('#save-config').click(function(){
  var valuesToSubmit = $('#mail-form').serialize();
  console.log(valueToSubmit);
  $.ajax({
    url: $('#mail-form').attr('action'), //sumbits it to the given url of the form
    data: valuesToSubmit,
    dataType: "JSON" // you want a difference between normal and ajax-calls, and json is standard
  }).success(function(json){
    //act on result.
  });
  return false; // prevents normal behaviour
});

Upvotes: 1

Related Questions