Display inline errors with simple_form in a Bootstrap Ajax modal

Deadly 提交于 2019-11-29 04:47:02

The main issue here was calling the form with data-type => :json. That means it will expect a JSON response, but I want it to pass back JavaScript. The solution is to set data-type => :script (or just leave it off and let Rails infer JavaScript):

:html => {:class => "form-horizontal", 
          "data-type" => :script }) do |contact_form| %>

Thanks to this article for explaining the various data-types, and clarifying that data-type refers to the response, not the submission of data:

Rails 3 Remote Links and Forms Part 2: Data-type (with jQuery)

"jQuery’s .ajax() method provides an optional parameter called dataType to specify the desired data-type of the response."

Another issue that I think @wanghq was pointing to is that JQuery's .html() method updates the innerHTML of an object. I wound up creating a partial containing only the form, calling the partial inside a <div id="new-contact-form-wrapper"> wrapper, then targeting the wrapper to replace the form:

var myForm = "<%= escape_javascript(render :partial => 'contacts/new_modal_form', :locals => { :contact => @contact.errors }) %>";
$("#new-contact-form-wrapper").html(myForm);

I am still working on getting variables passed, the form cleared on success, etc. Since I'm using a partial from the controller, I'll probably just go ahead and put all the JQuery (for both success and failure) in there so I won't need app/assets/javascripts/contacts.js.

I don't understand why you need reset the form. I think it's not necessary.

$(function($) {
  $("#new_contact")
    .bind("ajax:success", function(event, data, status, xhr) {
      ...
    })
});

One thing you need to fix is below line in your new_model_error.js.erb, otherwise you will have duplicate divs with id="new-contact-modal".

old:
$("#new-contact-modal").html($(modal)); 
new:
$("#new-contact-modal").html($(modal).html());

Let me know if you still have problem.

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!