Welcome to the Treehouse Community

Want to collaborate on code errors? Have bugs you need feedback on? Looking for an extra set of eyes on your latest project? Get support with fellow developers, designers, and programmers of all backgrounds and skill levels here with the Treehouse Community! While you're at it, check out some resources Treehouse students have shared here.

Looking to learn something new?

Treehouse offers a seven day free trial for new students. Get access to thousands of hours of content and join thousands of Treehouse students and alumni in the community today.

Start your free trial

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?

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:

myawesomejavascriptfile.js.coffee.whatever 

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.