Rails remote form and select on change not working
Asked Answered
B

4

8

I was trying to follow: Rails: submit (via AJAX) when drop-down option clicked

However none of these options appear to work (onsubmit, submit)

This is what I currently have that is refreshing the page:

= simple_form_for task, :remote => true, :format => :js do |f|`
    = f.association :status, :label => false, :include_blank => false, :input_html => {:onchange=>'this.form.submit();' }`

This simply posts the form regularly and causes the page to refresh.

How can I get it to post via ajax so the page won't refresh?

Bound answered 18/11, 2011 at 4:55 Comment(0)
P
5

Although rails overrides the default action and submits via AJAX when you add :remote => true, you are forcing the form to post the regular what in your onchange event.

You need to make your own function to submit via AJAX and call that from your onchange, using $.post() $.post() to send the form to the server.

Pent answered 18/11, 2011 at 23:35 Comment(0)
N
13

Just change your onchange to this instead:

{:onchange=>'$(this.form).submit();' }
Neruda answered 31/7, 2013 at 21:31 Comment(1)
This works fantastically without the need to code a manual handler or jump through additional hoops.Pesthole
P
5

Although rails overrides the default action and submits via AJAX when you add :remote => true, you are forcing the form to post the regular what in your onchange event.

You need to make your own function to submit via AJAX and call that from your onchange, using $.post() $.post() to send the form to the server.

Pent answered 18/11, 2011 at 23:35 Comment(0)
B
5

I ended up making a event bind as per Marc's suggestion

= simple_form_for task, :remote => true, :format => :js, :html => {:id => "task_#{task.id}_status"} do |f|
            = f.association :status, :label => false, :include_blank => false, :input_html => {:id => "task_#{task.id}_status_select" }

:javascript
        jQuery(function($) {
          $(document).ready(function() {
            $("#task_#{task.id}_status_select").bind("change", function() {
              $.ajax({
                type: "PUT",
                url: '#{project_story_type_story_task_path(@project, @story_type, @story, task)}',
                data: 'task[status_id]=' + $('#task_#{task.id}_status_select').val(),
                complete: function() {
                  $('#task_#{task.id}_status').prepend("<span id='task_#{task.id}_success' class='label success right'>SAVED</span>");
                  $('#task_#{task.id}_success').delay(500).fadeOut();

                }
              });
Bound answered 19/11, 2011 at 1:11 Comment(0)
E
0

You can use data: remote on the select directly to submit the change to the defined url.

= form_with model: task do |f|
  = f.label :status
  = f.select :status, collection, {}, data: {remote: true, method: 'PUT', url: task_path(task)}
Engineman answered 13/8 at 18:19 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.