:remote => true/data-remote on a form loaded via ajax
Asked Answered
A

1

4

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?

Attar answered 7/11, 2012 at 15:27 Comment(5)
You seem to be missing a closing parenthesis after url_forSmew
Side note: always have your javascript console open when debugging javascript. If something doesn't work, first point is to hunt down errors. With AJAX, be sure you have something like Chrome network monitor at the ready to see xhr requests and errors.Rosana
Zenph: not sure how this helps me in this particular case, since there is no javascript our internal server error.Attar
Did you ever figure this out? I'm seeing the same thing, content loaded via an ajax calls doesn't get recognized by the UJS stuff. It makes sense that the UJS stuff has already 'fired' on page load but I can't find anywhere that anybody talks about 're-firing' them for a partial.Phytoplankton
Unfortunately no. I had to change the way I was expecting to work with Ajax in my app.Attar
L
2

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.

Leninism answered 5/9, 2013 at 17:12 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.