Alex Marchant
Alex Marchant

Reputation: 2510

AJAX rails check box using javascript .submit()

I'm using Rails 3.1 and I need a checkbox to toggle and save to the database without the page refreshing or redirecting.

Let me preface by saying i'm fairly novice, if i'm coming at this problem from the wrong angle please let me know.

Here is my form:

<% form_for book, :remote => true do |f| %>
   <%= f.check_box :finished %>
<% end %>

Here is my jQuery javascript:

$('input#book_finished').live("click", function() {
    $(this).parent('form').submit();
});

The :remote = > true doesn't work when I submit via jQuery, but does if I throw in a submit button (which I can't have). How can I submit on clicking the checkbox though JS?

Upvotes: 2

Views: 4073

Answers (1)

polarblau
polarblau

Reputation: 17744

Your code so far only handles the submitting via a click on the checkbox. In order to submit the form via AJAX, you'll still have to catch the submit event, prevent the default behavior and send the form data:

$('#form-id').submit(function(){
  $.ajax({
    type: this.method,
    url: this.action,
    data: $(this).serialize(),
    success: function(){
      ... // do something in case everything went find
    }
  });
  return false;
});

Upvotes: 3

Related Questions