Welcome to the Treehouse Community

The Treehouse Community is a meeting place for developers, designers, and programmers of all backgrounds and skill levels to get support. Collaborate here on code errors or bugs that you need feedback on, or asking for an extra set of eyes on your latest project. Join thousands of Treehouse students and alumni in the community today. (Note: Only Treehouse students can comment or ask questions, but non-students are welcome to browse our conversations.)

Looking to learn something new?

Treehouse offers a seven day free trial for new students. Get access to thousands of hours of content and a supportive community. Start your free trial today.

Ruby Building Social Features in Ruby on Rails Using AJAX Implementing AJAX: Part 1

js versus json

I originally leanred to use AJAX via ryanbates tutorial in which he focuses on using js and creating js.erb templates. Once starting your video, I wondered about the pros and cons of the two approaches. I found this discussion helpful: http://stackoverflow.com/questions/8439938/ruby-on-rails-json-vs-js-ajax-response

Anyway, what are your thoughts on this?

Kevin Lozandier
Kevin Lozandier
Courses Plus Student 53,747 Points

Hi, Dale Hollocher:

You only need to add .erb to your js files if you want to use erb variables, values, and processing before your files gets compiles to JavaScript. Rails knows to handle a file a particular way before its final extension defined from right to left.

For example:


Rails will ultimately generate this file as a .js file, but will preprocess the file first as .coffee and .whatever, as long as the template handler or engine for a particular filetype is known to Rails.

When it comes to preprocessing with .erb, there are many reasons you may have to do prepend .erb, particularly AJAX-related tasks, is to refer to a particular instance of a model the JavaScript files needs to get the desired outcome you want.

It comes in handy if you don't have another alternative of getting the required information you need about something that was generated from your Rails App (do note there's many ways around this, the most obvious is use a JavaScript framework).

1 Answer

In my experience, ajax is really used for making your app more interactive (update content without reloading the page). JSON becomes handy when sending out or receiving in data from another website (ex: receiving the user profile data from twitter as a hash).

Of course both Ajax and Json can work together.