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?

razenha
  • 7,660
  • 6
  • 37
  • 53
  • You seem to be missing a closing parenthesis after `url_for` – PinnyM Nov 07 '12 at 15:30
  • 1
    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. – Damien Roche Nov 07 '12 at 17:50
  • Zenph: not sure how this helps me in this particular case, since there is no javascript our internal server error. – razenha Nov 08 '12 at 04:17
  • 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. – Mark G Mar 03 '13 at 20:36
  • Unfortunately no. I had to change the way I was expecting to work with Ajax in my app. – razenha Mar 04 '13 at 21:10

1 Answers1

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.

Zajo
  • 362
  • 2
  • 14