:remote => true/data-remote on a form loaded via a

2019-04-09 23:30发布

问题:

In my Rails app, I have a form that is loaded via Ajax using jQuery load method.

function load_sales_form(product_id) {
    $("#sales_form").load("<%= url_for(:action => :show_sales_form) %>"/ + product_id);
}

The loaded form has a form_for tag with the :remote => true option and it does add the data-remote="true" attribute to the form.

But the form isn't submitted using Ajax when the user clicks the submit tag button. It works fine if the form is loaded in the standard, non-ajax way, but it the form is loaded via ajax after the document is ready, is does not submit using ajax, it submits as a standard form.

From what I studied so far, this happens because the rails.js file (which contains the stuff that allow data-remote forms to be submitted via ajax) does not apply it's features to html content loaded via ajax.

Is it possible to force rails.js file to apply it's features to content loaded via Ajax?

回答1:

Same situation here. I found a solution. Not the dynamic loading, but incorrect triggering of submit event was the cause in my case.

I had a Bootstrap modal with data-target and href attributes set. This causes the content inside a .modal-body to be loaded via AJAX from address specified in href.

The modal was pre-equipped with save button (outside of the loaded form), which called the submit like this.

$modal.find("form.loaded_form").get(0).submit(); // INCORRECT

The former only executes raw submit, but:

$modal.find("form.loaded_form").trigger('submit'); // CORRECT

does the trick.