Rails turbolinks break submit remote form

半城伤御伤魂 提交于 2019-11-30 23:25:14

Turbolinks

As mentioned, the problem with Turbolinks is that it reloads the <body> part of the DOM with an ajax call - meaning JS is not reloaded, as it's in the head

The typical way around this issue is to delegate your JS from the document, like this:

$(document).on("click", "#your_element", function() {
    //your code here
});

Because document is always going to be present, it will trigger the JS continuously


Remote

With your issue, it's slightly more tricky

The problem is you're relying on the JQuery UJS (unobtrusive JavaScript) engine of Rails, which is difficult to remedy on its own

We've never had this issue & we use Turbolinks all the time - so I suppose the problem could be with how you're constructing your form / handling the request. This GitHub seemed to recreate the issue, and it was to do with the table

Maybe you could try:

<%= form_for [object], remote: true do |f| %>                                                   
    <%= f.text_field :name, class: 'form-control' %>                                     
    <%= f.email_field :email, class: 'form-control' %>                              
    <%= f.submit button_name, class: 'btn btn-sm btn-primary' %>
<% end %>    

Turbolinks don't fully reload your page, but only part of it. This is what makes them so fast, however if you have JavaScript requiring a full page reload you will run into trouble. The reason it does work with a refresh is because now you force the page to fully reload.

Edit: This gem might be worth trying out: https://github.com/kossnocorp/jquery.turbolinks

For a little bit of extra information about the inner workings of turbolinks: http://guides.rubyonrails.org/working_with_javascript_in_rails.html#turbolinks

Or: https://github.com/rails/turbolinks

P.s. Also make sure the javascript_include_tag is within the head tag (and not in the body)

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