1

I am reading the Rails guides, in particular I am reading this: http://guides.rubyonrails.org/working_with_javascript_in_rails.html#server-side-concerns The part that is a little bit confusing to me is the response. It says that if the create action receives an AJAX request then it will return the javascript code that will insert the user in the page. I have found other solutions in which the client receives a json object (instead of javascript code) and builds the corresponding DOM elements and inserts them in the page. My questions are:

  1. Is it a better to receive json objects and build DOM elements and insert them on the page than receive javascript code and execute it so that new content gets added to the page? What are the best practices about it?
  2. In this example, what will the ajax call receive? javascript code, a json object or both?

1 Answer 1

1

There is no right or wrong way. In the example you cited, the ajax call will receive javascript which it will then execute in the browser. However, it is likely that you will want to embed html in the javascript response. For example, here is a rails partial inserted in the response:

Controller:

def create
   @user=User.new(:user_params)
   @user.save
   respond_to do |format|
     format.js()
   end
end

View:create.js

$("#user_list").append('<%=render(partial:'user_row')%>')

Partial: _user_row.html.erb

<div class="user-row"><%[email protected]%></div>

The partial will automatically have access to variables in the create controller method. If the html you would like to insert is large or complicated, this could greatly simplify your code and make it more readable.

In order to do the same thing while responding with json, you would, as you said, have to manually build the DOM element. You would prefer to build the DOM element manually if server resources were limited, or if you preferred to limit the amount of data you were sending over the network. Note, that when you respond with json, most of the work is done in the browser and you only have to send a json object, as opposed to javascript with embedded html.

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.