Working with JavaScript in Rails ================================ This guide covers the built-in Ajax/JavaScript functionality of Rails (and more); it will enable you to create rich and dynamic Ajax applications with ease! After reading this guide, you will know: * Quick introduction to Ajax. * Unobtrusive JavaScript. * How Rails' built-in helpers assist you. * Handling Ajax on the server side. * The Turbolinks gem. ------------------------------------------------------------------------------- An Introduction to Ajax ------------------------ In order to understand Ajax, you must first understand what a web browser does normally. When you type `http://localhost:3000` into your browser's address bar and hit 'Go,' the browser (your 'client') makes a request to the server. It parses the response, then fetches all associated assets, like JavaScript files, stylesheets and images. It then assembles the page. If you click a link, it does the same process: fetch the page, fetch the assets, put it all together, show you the results. This is called the 'request response cycle.' JavaScript can also make requests to the server, and parse the response. It also has the ability to update information on the page. Combining these two powers, a JavaScript writer can make a web page that can update just parts of itself, without needing to get the full page data from the server. This is a powerful technique that we call Ajax. Rails ships with CoffeeScript by default, and so the rest of the examples in this guide will be in CoffeeScript. All of these lessons, of course, apply to vanilla JavaScript as well. As an example, here's some CoffeeScript code that makes an Ajax request using the jQuery library: ```coffeescript $.ajax(url: "/test").done (html) -> $("#results").append html ``` This code fetches data from "/test", and then appends the result to the `div` with an id of `results`. Rails provides quite a bit of built-in support for building web pages with this technique. You rarely have to write this code yourself. The rest of this guide will show you how Rails can help you write web sites in this manner, but it's all built on top of this fairly simple technique. Unobtrusive JavaScript ------------------------------------- Rails uses a technique called "Unobtrusive JavaScript" to handle attaching JavaScript to the DOM. This is generally considered to be a best-practice within the frontend community, but you may occasionally read tutorials that demonstrate other ways. Here's the simplest way to write JavaScript. You may see it referred to as 'inline JavaScript': ```html Here ``` When clicked, the alert will trigger. Here's the problem: what happens when we have lots of JavaScript we want to execute on a click? ```html Calculate ``` Awkward, right? We could pull the function definition out of the click handler, and turn it into CoffeeScript: ```coffeescript fib = (n) -> (if n < 2 then n else fib(n - 1) + fib(n - 2)) ``` And then on our page: ```html Calculate ``` That's a little bit better, but what about multiple links that have the same effect? ```html Calculate Calculate Calculate ``` Not very DRY, eh? We can fix this by using events instead. We'll add a `data-*` attribute to our link, and then bind a handler to the click event of every link that has that attribute: ```coffeescript fib = (n) -> (if n < 2 then n else fib(n - 1) + fib(n - 2)) $(document).ready -> $("a[data-fib]").click (e) -> count = $(this).data("fib") alert "fib of #{count} is: #{fib(count)}." ... later ... Calculate Calculate Calculate ``` We call this 'unobtrusive' JavaScript because we're no longer mixing our JavaScript into our HTML. We've properly separated our concerns, making future change easy. We can easily add behavior to any link by adding the data attribute. We can run all of our JavaScript through a minimizer and concatenator. We can serve our entire JavaScript bundle on every page, which means that it'll get downloaded on the first page load and then be cached on every page after that. Lots of little benefits really add up. The Rails team strongly encourages you to write your CoffeeScript (and JavaScript) in this style, and you can expect that many libraries will also follow this pattern. Built-in Helpers ---------------------- Rails provides a bunch of view helper methods written in Ruby to assist you in generating HTML. Sometimes, you want to add a little Ajax to those elements, and Rails has got your back in those cases. Because of Unobtrusive JavaScript, the Rails "Ajax helpers" are actually in two parts: the JavaScript half and the Ruby half. [rails.js](https://github.com/rails/jquery-ujs/blob/master/src/rails.js) provides the JavaScript half, and the regular Ruby view helpers add appropriate tags to your DOM. The CoffeeScript in rails.js then listens for these attributes, and attaches appropriate handlers. ### form_for [`form_for`](http://api.rubyonrails.org/classes/ActionView/Helpers/FormHelper.html#method-i-form_for) is a helper that assists with writing forms. `form_for` takes a `:remote` option. It works like this: ```erb <%= form_for(@post, remote: true) do |f| %> ... <% end %> ``` This will generate the following HTML: ```html
``` Note the `data-remote='true'`. Now, the form will be submitted by Ajax rather than by the browser's normal submit mechanism. You probably don't want to just sit there with a filled out ` ``` Since it's just a `