views:

336

answers:

1

In a Rails 3 app, I want to make the browser call a remote function whenever a certain checkbox is toggled. In Rails 2, this was easy to do by passing

:onclick => remote_function(...)

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

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

In the rails.js file that comes bundled with Rails is an observer that listens for submit events. However, these only seem to be triggered when the user clicks on a submit button, but not when form.submit() is called (so far tested only in FF).

This has the unwanted effect that the submit is then not done in the background via AJAX, but the normal way, so the browser leaves the current site and displays the response from the controller.

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

A: 

You can submit the form by calling:

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

This will submit the form using AJAX to the url given to form_tag and evaluate received response, so it has to respond with JS. Change the onSuccess implementation if you don't want that.

If the form submission is a workaround, as you say, then instead of submitting the whole form you could also handle the on-click event on the check-box manually and send an AJAX request:

<%= 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
      }
    })
  });
});
Matt