title: Returning HTML to AJAX Rails calls
body: <p>After reading David Heinemeier Hansson's <a href="https://37signals.com/svn/posts/3697-server-generated-javascript-responses" rel="noreferrer">blog post</a> about server-generated javascript I decided to review the way I approach making AJAX calls in my Rails applications. What David suggests is to create a <code>.js.erb</code> template, which is just javascript embedded with ruby code generated on the server, and not to do any DOM manipulation in the client-side javascript.</p>
  
  <p>Another approach is of course to simply do everything on the client-side, and (for example) return a JSON object representing the updated object from the server and use javascript to do all DOM manipulation.</p>
  
  <p>I dislike the first approach for two reasons: </p>
  
  <p>1) I use HAML and Coffeescript in my application, and feel that by using vanilla javascript and ERB would uncecessarily bloat my code-base with code of a different language (maybe it's possible to create .coffee.haml templates rather than js.erb, I don't know)</p>
  
  <p>2) I really don't like the idea of 'littering' my view folder with what is essentially javascript files, with a little bit of ruby embedded.</p>
  
  <p>The second approach, as David talks about in his blog post, relies very heavily on client-side javascript, which could lead to bloated client-side javascript code, and possibly the need for client-side templates, which in worst case scenarios could mean almost doubling the number of templates.</p>
  
  <p>The approach I decided to go for (and want to ask whether or not is completely stupid way to go about this) is the following:</p>
  
  <p>1) Set the <code>remote: true</code> flag to make links and forms utilize AJAX to post to the server.</p>
  
  <p>2) In my controller, handle everything as html, and simply render without layout should the request be an AJAX request: <code>render partial: '&lt;partial-name&gt;', layout: false if request.xhr?</code>. This simply returns the HTML of the partial, with the ruby code evaluated.</p>
  
  <p>3) In an asset javascript file (for instance <code>&lt;partial-name&gt;.js.coffee</code>) listen to <code>ajax:success</code> and append the HTML from the response.</p>
  
  <p>I like this approach because (in my rather simple application) this allows me to keep all my code in HAML/Coffeescript, and avoids any javascript templates. </p>
  
  <p>I realize this problem might take on a different character should the complexity of the application grow, but I still feel that it's a valid question: is this a bad way to go about implementing an AJAX-based architecture for a Rails application (and if so, why? i.e. is there a reason why returning HTML instead of JSON from an AJAX call is a bad idea?) or is this something I should continue to utilize?</p>
  
  <p>Thank you :-)</p>