I’ve read a lot of Ruby on Rails books, including Head First Rails, Ruby on Rails Up and Running, The Rails View, and also some Brazilian authors.
Something was still wrong. I thought to myself “but wouldn’t be a lot better if I requested some data and a callback function handled this data for me? Every Ajax book I’ve seen teaches me to do this! Why should it be so difficult with Rails?”
In fact, it’s not. It’s really easy. And it makes more sense.
Why would they pack Rails with CoffeeScript, if the controller would process a “js.erb”? You can and should handle the response with a CoffeeScript callback.
How to do that? Simple enough:
$(document).ready -> $("a#link_id").bind "ajax:complete", (e, xhr, settings) -> # TODO: the callback function goes here
You can put whatever you want to identify your link (or form) instead of “a#link_id”. Of course you can define the callback function outside of the bind and pass it as a parameter.
The content of the response is inside of xhr.responseText. For example, if you requested a JSON, you can do that:
response = jQuery.parseJSON(xhr.responseText)
And you’ll have all the data from the server.
There are also other Ajax events that may help your page to have a more responsive interface:
ajax:complete (it is after a success OR a failure, so don’t use it instead of ajax:success)
ajax:after (after the request is sent, not after the response was processed)
I needed each of these submit buttons to show my data in a different way. But the data I needed would be always the same. I could use three links and update them whenever the select changed, but this would not be practical at all. This was a lot simpler:
$("#report").bind "mousedown", -> $("form").bind("ajax:complete", reportCallback) $("#graph").bind "mousedown", -> $("form").bind("ajax:complete", graphCallback) $("#pizza").bind "mousedown", -> $("form").bind("ajax:complete", pizzaCallback)
There are situations where two different pages also need the same data, but they will also process them differently. A callback function would also be the best approach for it. As a general rule, getting data and processing it with a callback function will almost always be better.