Form.submit () skipped rails.js UJS Observer

In a Rails 3 application, I want the browser to call a remote function whenever a certain checkbox is selected. In Rails 2, this was easy to do by skipping

:onclick => remote_function(...)

to the checkbox. In Rails 3, the remote_ * functions are deprecated, so I tried the following workaround:

  • create a shape around the checkbox with form_tag ... :remote => true
  • submit the form by calling $("dummy_form").submit();from the handleronclick

The rails.js file that comes with Rails has an observer that listens for events submit. However, it seems that this only works when the user presses the submit button, but not when it is called form.submit()(so far only verified in FF).

This has an undesirable effect that the submission is then not performed in the background via AJAX, but in the usual way, so the browser leaves the current site and displays a response from the controller.

Does anyone know a workaround? Maybe a completely different way to get the same functionality?

+5
source share
1 answer

You can submit the form by calling:

$("dummy_form").request({
    onSuccess: function(response) {eval(response)}
});

This will result in submitting the form using AJAX to the URL provided by form_tag and evaluating the response received, so it should respond with JS. Change the implementation of onSuccess if you do not want to.

, , , , on-click AJAX:

<%= javascript_tag do %>
Event.observe(window, 'load', function() {
  $('CHECK_BOX_ID').observe('click', function(event) {
    new Ajax.Request('/your/url', {
      onSuccess: function(response) {
        // yada yada yada
      }
    })
  });
});
+1

All Articles