After coming across David Heinemeier Hansson's interesting blog post regarding server-generated javascript, I was inspired to reassess my approach to handling AJAX calls within my Rails applications. According to David, the recommended method is to create a .js.erb
template, which merges javascript with ruby code generated on the server, eliminating any need for DOM manipulation in client-side javascript.
Alternatively, one could opt to handle everything purely on the client-side by returning a JSON object representing the updated data from the server and utilizing javascript for all DOM manipulations.
I have reservations about the former approach for two main reasons:
1) Personally, I prefer using HAML and Coffeescript in my application, and incorporating vanilla javascript and ERB might introduce unnecessary complexity to my codebase by mixing languages (though I'm unsure if it's feasible to create .coffee.haml templates instead of js.erb).
2) The idea of cluttering my view folder with essentially javascript files containing snippets of embedded ruby does not sit well with me.
The latter approach, as outlined by David in his blog post, heavily relies on client-side javascript, potentially resulting in bloated javascript code and requiring client-side templates, possibly doubling the number of templates needed in extreme cases.
Therefore, after careful consideration, I have chosen to pursue a different strategy - setting the remote: true
flag to enable links and forms to utilize AJAX for posting to the server.
In the controller, I handle everything as html and simply render without layout should the request be an AJAX request:
render partial: '<partial-name>', layout: false if request.xhr?
. This approach returns the HTML of the partial along with evaluated ruby code.
In an asset javascript file (such as <partial-name>.js.coffee
), I listen for ajax:success
events and append the received HTML content.
I find this method appealing because it allows me to maintain all my code in HAML/Coffeescript, omitting the need for javascript templates.
While I acknowledge that this solution may pose challenges as the application complexity increases, I still believe it raises a valid question: Is adopting this approach a poor choice for implementing AJAX functionality in a Rails application? Should I continue with this method or reconsider my approach? Are there disadvantages to returning HTML instead of JSON from an AJAX call? Your feedback is appreciated. :-)