Need to allow forms to be resubmitted Rails AJAX

2019-08-16 08:13发布

问题:

I'm writing an app where I want to be able to add people to a department via AJAX, but though I can remove many times, I can't add more than once. It seems that the form can't be submitted multiple times. I'm using a partial (that contains the two types of forms). The only difference is that there is only one "add-form" and many "remove-forms" (since you can be in many departments at once).

<td><%= form_tag remove_department_person_path(:id => @person.id, :department => department), :method => :post, :class => "remove_form", :remote => true  do %>
<% submit_tag "Remove", :class => "btn"%><% end %></td>

Is generated several times

<%= form_tag add_department_person_path(:id => @person.id), :method => :post, :remote => true, :class => "add_form" do %>
  <td>
    <%= select_tag 'department', options_for_select(@unassigned)%>
  </td>
  <td>
    <%= text_field_tag :title %>
  </td>
  <td>
    <%= submit_tag "Add", :class => "btn add-btn"%>
  </td>
<% end %>

Is generated once. My javascript is

$('.remove_form').on('ajax:success', function(event,data) {
  d = jQuery.parseJSON(data)
  $('#departments').html(d.html)
  return false
})
$('.add_form').live('ajax:success', function(event,data) {
  d = jQuery.parseJSON(data)
  $('#departments').html(d.html)
  return false
})

This is re-run every time the partial is reloaded so that shouldn't be the problem. Any suggestions?

回答1:

Discovered that the problem was (at least partially) due to the way that rails handles AJAX - the event handlers only go off once.

function updateForms(data) {
  $('#departments').html($("<div>"+data+"</div>").find("#departments").html())
  setAjax()
  return false
}

function setAjax() {
  $('#deplist').on('submit', '.remove_form', function(e) {
    $.rails.handleRemote( $(this) );
    e.preventDefault();
  });
  $('.add_form').on('submit', function(e) {
    $.rails.handleRemote( $(this) );
    e.preventDefault();
  });
  $('.remove_form').on('ajax:success', function(event,data) {
    updateForms(data)
  })
  $('.add_form').on('ajax:success', function(event,data) {
    updateForms(data)
  })
}

I was given the basis for this code from another stack overflow question and I'll link to that if I can find it again