mvilrokx
mvilrokx

Reputation: 1658

Should you return javascript (.js.erb) from the Rails server OR use the native JS callback mechanism when updating the page after a Ajax call

I am doing an ajax call (using JQuery) and the Rails controller needs to return a partial so I can update the page after the ajax call. It seems to me there are 2 ways of doing this. In the controller, you filter for ajax calls (request.xhr?) and return:

  1. a .js.erb which gets executed on the client side as part of the Ajax call itself (dataType : script). This .js.erb file manipulates the DOM and injects the partials' html, something like this:

    $('#content').html("<%= escape_JavaScript(render :partial => 'success') %>");

  2. a partial ((dataType : html). You have a success callback method on the ajax call that then performs the inject, something like this:

    $.post( url, send_data, function( data ) { $( "#result" ).empty().append( data ); }

These 2 solutions both work perfectly, I just don't know which one is considered better coding practice and easier to maintain down the line.

Upvotes: 2

Views: 794

Answers (2)

RyanWilcox
RyanWilcox

Reputation: 13974

I would say the second option too, because it makes sense when talking from a RESTful perspective.

I talk about this in a blog entry "Rails, REST and JS - We're doing it wrong"

Upvotes: 0

jmulligan
jmulligan

Reputation: 104

The second option is ideal. The Server should never be concerned with the Client.

Upvotes: 1

Related Questions