Hacker News new | ask | show | jobs
by kp212 5715 days ago
I picked up Ruby and then RoR about 8 weeks ago. I was stuck on this issue:

http://stackoverflow.com/questions/4020393/ruby-on-rails-3-f...

  If you are an expert on 3.0/UJS (can't seem to find as much 
documentation /tutorials on this), I'd even pay a nominal amount just to email you a few questions over the next few months as I learn.
1 comments

In Rails 3, the javascript drivers are very hands-off (i.e. unobtrusive). The problem you're having is that your app is returning to the browser a string of javascript, but there is nothing in the page that is then executing that javascript in the context of the page.

In your original page, along with the form, you need to bind an event to the form's "ajax:success" event.

The rails.js ujs driver binds to forms and links with "data-remote=true", which is what the ":remote => true" is doing, to make them submit their requests remotely, but that is where the Rails magic stops.

The good news is that the remote requests fires off some events you can bind to, which give you access to the data returned by the server (which fire off in the following order):

  ajax:before
  ajax:loading
  ajax:success
  ajax:complete
  ajax:failure
  ajax:after
You need to bind an event to the ajax:success event of your form. So, if your form had the id "myform", you'd want something like this on your page:

  $('#myform').bind('ajax:success', function(evt, data, status, xhr){
    xhr.responseText;
  });
xhr.responseText is what your server returns, so this simply executes it as javascript.

Of course, it's proper to also bind to the failure event with some error handling as well.

I usually don't even use the action.js.erb method of returning javascript, I just have my controller render the HTML partial, and then I have a binding like this in the page:

  $('#myform').bind('ajax:success', function(evt, data, status, xhr){
    $('#target-div').html(xhr.responseText);
  });