Skip to content
This repository
Browse code

Working With JavaScript guide.

Originally, this guide was called "AJAX on Rails," but really, it's
not just about AJAX. This was never finished, but it got accidentally
generated and Google found out about it.

In the meantime, all the guides were converted to markdown, as well.

So here's a new guide. It covers all of the built-in helpers that
use ajax requests, it covers CoffeeScript, and it covers UJS.
  • Loading branch information...
commit 4d0c43e66c112d551eb8a167a35ddf2d7866fcc0 1 parent 59b8b82
Steve Klabnik authored August 30, 2012
316  guides/source/ajax_on_rails.md
Source Rendered
... ...
@@ -1,316 +0,0 @@
1  
-AJAX on Rails
2  
-=============
3  
-
4  
-This guide covers the built-in Ajax/JavaScript functionality of Rails (and more);
5  
-it will enable you to create rich and dynamic AJAX applications with ease! We will
6  
-cover the following topics:
7  
-
8  
-* Quick introduction to AJAX and related technologies
9  
-* Unobtrusive JavaScript helpers with drivers for Prototype, jQuery etc
10  
-* Testing JavaScript functionality
11  
-
12  
---------------------------------------------------------------------------------
13  
-
14  
-Hello AJAX - a Quick Intro
15  
---------------------------
16  
-
17  
-AJAX is about updating parts of a web page without reloading the page. An AJAX
18  
-call happens as a response to an event, like when the page finished loading or
19  
-when a user clicks on an element. For example, let say you click on a link, which
20  
-would usually take you to a new page, but instead of doing that, an asynchronous
21  
-HTTP request is made and the response is evaluated with JavaScript. That way the
22  
-page is not reloaded and new information can be dynamically included in the page.
23  
-The way that happens is by inserting, removing or changing parts of the DOM. The
24  
-DOM, or Document Object Model, is a convention to represent the HTML document as
25  
-a set of nodes that contain other nodes. For example, a list of names is represented
26  
-as a `ul` element node containing several `li` element nodes. An AJAX call can
27  
-be made to obtain a new list item to include, and append it inside a `li` node to
28  
-the `ul` node.
29  
-
30  
-### Asynchronous JavaScript + XML
31  
-
32  
-AJAX means Asynchronous JavaScript + XML. Asynchronous means that the page is not
33  
-reloaded, the request made is separate from the regular page request. JavaScript
34  
-is used to evaluate the response and the XML part is a bit misleading as XML is
35  
-not required, you respond to the HTTP request with JSON or regular HTML as well.
36  
-
37  
-### The DOM
38  
-
39  
-The DOM (Document Object Model) is a convention to represent HTML (or XML)
40  
-documents, as a set of nodes that act as objects and contain other nodes. You can
41  
-have a `div` element that contains other `div` elements as well as `p` elements
42  
-that contain text.
43  
-
44  
-### Standard HTML communication vs AJAX
45  
-
46  
-In regular HTML comunications, when you click on a link, the browser makes an HTTP
47  
-`GET` request, the server responds with a new HTML document that the browsers renders
48  
-and then replaces the previous one. The same thing happens when you click a button to
49  
-submit a form, except that you make and HTTP `POST` request, but you also get a new
50  
-HTML document that the browser renders and replaces the current one. In AJAX
51  
-communications, the request is separate, and the response is evaluated in JavaScript
52  
-instead of rendered by the browser. That way you can have more control over the content
53  
-that gets returned, and the page is not reloaded.
54  
-
55  
-Built-in Rails Helpers
56  
-----------------------
57  
-
58  
-Rails 4.0 ships with [jQuery](http://jquery.com) as the default JavaScript library.
59  
-The Gemfile contains `gem 'jquery-rails'` which provides the `jquery.js` and
60  
-`jquery_ujs.js` files via the asset pipeline.
61  
-
62  
-You will have to use the `require` directive to tell Sprockets to load `jquery.js`
63  
-and `jquery.js`. For example, a new Rails application includes a default
64  
-`app/assets/javascripts/application.js` file which contains the following lines:
65  
-
66  
-```
67  
-// ...
68  
-//= require jquery
69  
-//= require jquery_ujs
70  
-// ...
71  
-```
72  
-
73  
-The `application.js` file acts like a manifest and is used to tell Sprockets the
74  
-files that you wish to require. In this case, you are requiring the files `jquery.js`
75  
-and `jquery_ujs.js` provided by the `jquery-rails` gem.
76  
-
77  
-If the application is not using the asset pipeline, this can be accessed as:
78  
-
79  
-```ruby
80  
-javascript_include_tag :defaults
81  
-```
82  
-
83  
-By default, `:defaults` loads jQuery.
84  
-
85  
-You can also choose to use Prototype instead of jQuery and specify the option
86  
-using `-j` switch while generating the application.
87  
-
88  
-```bash
89  
-rails new app_name -j prototype
90  
-```
91  
-
92  
-This will add the `prototype-rails` gem to the Gemfile and modify the
93  
-`app/assets/javascripts/application.js` file:
94  
-
95  
-```
96  
-// ...
97  
-//= require prototype
98  
-//= require prototype_ujs
99  
-// ...
100  
-```
101  
-
102  
-You are ready to add some AJAX love to your Rails app!
103  
-
104  
-### Examples
105  
-
106  
-To make them working with AJAX, simply pass the `remote: true` option to
107  
-the original non-remote method.
108  
-
109  
-```ruby
110  
-button_to 'New', action: 'new', form_class: 'new-thing'
111  
-```
112  
-
113  
-will produce
114  
-
115  
-```html
116  
-<form method="post" action="/controller/new" class="new-thing">
117  
-  <div><input value="New" type="submit" /></div>
118  
-</form>
119  
-```
120  
-
121  
-```ruby
122  
-button_to 'Create', action: 'create', remote: true, form: { 'data-type' => 'json' }
123  
-```
124  
-
125  
-will produce
126  
-
127  
-```html
128  
-<form method="post" action="/images/create" class="button_to" data-remote="true" data-type="json">
129  
-  <div><input value="Create" type="submit" /></div>
130  
-</form>
131  
-```
132  
-
133  
-```ruby
134  
-button_to 'Delete Image', { action: 'delete', id: @image.id },
135  
-             method: :delete, data: { confirm: 'Are you sure?' }
136  
-```
137  
-
138  
-will produce
139  
-
140  
-```html
141  
-<form method="post" action="/images/delete/1" class="button_to">
142  
-  <div>
143  
-    <input type="hidden" name="_method" value="delete" />
144  
-    <input data-confirm='Are you sure?' value="Delete" type="submit" />
145  
- </div>
146  
-</form>
147  
-```
148  
-
149  
-```ruby
150  
-button_to 'Destroy', 'http://www.example.com',
151  
-             method: 'delete', remote: true, data: { disable_with: 'loading...', confirm: 'Are you sure?' }
152  
-```
153  
-
154  
-will produce
155  
-
156  
-```html
157  
-<form class='button_to' method='post' action='http://www.example.com' data-remote='true'>
158  
-  <div>
159  
-    <input name='_method' value='delete' type='hidden' />
160  
-    <input value='Destroy' type='submit' data-disable-with='loading...' data-confirm='Are you sure?' />
161  
-  </div>
162  
-</form>
163  
-```
164  
-
165  
-### The Quintessential AJAX Rails Helper: link_to_remote
166  
-
167  
-Let's start with what is probably the most often used helper: `link_to_remote`. It has an interesting feature from the documentation point of view: the options supplied to `link_to_remote` are shared by all other AJAX helpers, so learning the mechanics and options of `link_to_remote` is a great help when using other helpers.
168  
-
169  
-The signature of `link_to_remote` function is the same as that of the standard `link_to` helper:
170  
-
171  
-```ruby
172  
-def link_to_remote(name, options = {}, html_options = nil)
173  
-```
174  
-
175  
-And here is a simple example of link_to_remote in action:
176  
-
177  
-```ruby
178  
-link_to_remote "Add to cart",
179  
-  :url => add_to_cart_url(product.id),
180  
-  :update => "cart"
181  
-```
182  
-
183  
-* The very first parameter, a string, is the text of the link which appears on the page.
184  
-* The second parameter, the `options` hash is the most interesting part as it has the AJAX specific stuff:
185  
-    * **:url** This is the only parameter that is always required to generate the simplest remote link (technically speaking, it is not required, you can pass an empty `options` hash to `link_to_remote` - but in this case the URL used for the POST request will be equal to your current URL which is probably not your intention). This URL points to your AJAX action handler. The URL is typically specified by Rails REST view helpers, but you can use the `url_for` format too.
186  
-    * **:update** Specifying a DOM id of the element we would like to update. The above example demonstrates the simplest way of accomplishing this - however, we are in trouble if the server responds with an error message because that will be injected into the page too! However, Rails has a solution for this situation:
187  
-
188  
-        ```ruby
189  
-        link_to_remote "Add to cart",
190  
-          :url => add_to_cart_url(product),
191  
-          :update => { :success => "cart", :failure => "error" }
192  
-        ```
193  
-
194  
-        If the server returns 200, the output of the above example is equivalent to our first, simple one. However, in case of error, the element with the DOM id `error` is updated rather than the `cart` element.
195  
-
196  
-    * **position** By default (i.e. when not specifying this option, like in the examples before) the response is injected into the element with the specified DOM id, replacing the original content of the element (if there was any). You might want to alter this behavior by keeping the original content - the only question is where to place the new content? This can specified by the `position` parameter, with four possibilities:
197  
-      * `:before` Inserts the response text just before the target element. More precisely, it creates a text node from the response and inserts it as the left sibling of the target element.
198  
-      * `:after` Similar behavior to `:before`, but in this case the response is inserted after the target element.
199  
-      * `:top` Inserts the text into the target element, before its original content. If the target element was empty, this is equivalent with not specifying `:position` at all.
200  
-      * `:bottom` The counterpart of `:top`: the response is inserted after the target element's original content.
201  
-
202  
-            A typical example of using `:bottom` is inserting a new \<li> element into an existing list:
203  
-
204  
-            ```ruby
205  
-            link_to_remote "Add new item",
206  
-              :url => items_url,
207  
-              :update => 'item_list',
208  
-              :position => :bottom
209  
-            ```
210  
-
211  
-    * **:method** Most typically you want to use a POST request when adding a remote
212  
-link to your view so this is the default behavior. However, sometimes you'll want to update (PATCH/PUT) or delete/destroy (DELETE) something and you can specify this with the `:method` option. Let's see an example for a typical AJAX link for deleting an item from a list:
213  
-
214  
-        ```ruby
215  
-        link_to_remote "Delete the item",
216  
-          :url => item_url(item),
217  
-          :method => :delete
218  
-        ```
219  
-
220  
-        Note that if we wouldn't override the default behavior (POST), the above snippet would route to the create action rather than destroy.
221  
-
222  
-    * **JavaScript filters** You can customize the remote call further by wrapping it with some JavaScript code. Let's say in the previous example, when deleting a link, you'd like to ask for a confirmation by showing a simple modal text box to the user. This is a typical example what you can accomplish with these options - let's see them one by one:
223  
-        * `:condition` =&gt; `code` Evaluates `code` (which should evaluate to a boolean) and proceeds if it's true, cancels the request otherwise.
224  
-        * `:before` =&gt; `code` Evaluates the `code` just before launching the request. The output of the code has no influence on the execution. Typically used show a progress indicator (see this in action in the next example).
225  
-        * `:after` =&gt; `code` Evaluates the `code` after launching the request. Note that this is different from the `:success` or `:complete` callback (covered in the next section) since those are triggered after the request is completed, while the code snippet passed to `:after` is evaluated after the remote call is made. A common example is to disable elements on the page or otherwise prevent further action while the request is completed.
226  
-        * `:submit` =&gt; `dom_id` This option does not make sense for `link_to_remote`, but we'll cover it for the sake of completeness. By default, the parent element of the form elements the user is going to submit is the current form - use this option if you want to change the default behavior. By specifying this option you can change the parent element to the element specified by the DOM id `dom_id`.
227  
-        * `:with` &gt; `code` The JavaScript code snippet in `code` is evaluated and added to the request URL as a parameter (or set of parameters). Therefore, `code` should return a valid URL query string (like "item_type=8" or "item_type=8&sort=true"). Usually you want to obtain some value(s) from the page - let's see an example:
228  
-
229  
-            ```ruby
230  
-            link_to_remote "Update record",
231  
-              :url => record_url(record),
232  
-              :method => :patch,
233  
-              :with => "'status=' + 'encodeURIComponent($('status').value) + '&completed=' + $('completed')"
234  
-            ```
235  
-
236  
-            This generates a remote link which adds 2 parameters to the standard URL generated by Rails, taken from the page (contained in the elements matched by the 'status' and 'completed' DOM id).
237  
-
238  
-    * **Callbacks** Since an AJAX call is typically asynchronous, as its name suggests (this is not a rule, and you can fire a synchronous request - see the last option, `:type`) your only way of communicating with a request once it is fired is via specifying callbacks. There are six options at your disposal (in fact 508, counting all possible response types, but these six are the most frequent and therefore specified by a constant):
239  
-      * `:loading:` =&gt; `code` The request is in the process of receiving the data, but the transfer is not completed yet.
240  
-      * `:loaded:` =&gt; `code` The transfer is completed, but the data is not processed and returned yet
241  
-      * `:interactive:` =&gt; `code` One step after `:loaded`: The data is fully received and being processed
242  
-      * `:success:` =&gt; `code` The data is fully received, parsed and the server responded with "200 OK"
243  
-      * `:failure:` =&gt; `code` The data is fully received, parsed and the server responded with **anything** but "200 OK" (typically 404 or 500, but in general with any status code ranging from 100 to 509)
244  
-      * `:complete:` =&gt; `code` The combination of the previous two: The request has finished receiving and parsing the data, and returned a status code (which can be anything).
245  
-      * Any other status code ranging from 100 to 509: Additionally you might want to check for other HTTP status codes, such as 404. In this case simply use the status code as a number:
246  
-
247  
-            ```ruby
248  
-            link_to_remote "Add new item",
249  
-              :url => items_url,
250  
-              :update => "item_list",
251  
-              404 => "alert('Item not found!')"
252  
-            ```
253  
-
254  
-            Let's see a typical example for the most frequent callbacks, `:success`, `:failure` and `:complete` in action:
255  
-
256  
-            ```ruby
257  
-            link_to_remote "Add new item",
258  
-              :url => items_url,
259  
-              :update => "item_list",
260  
-              :before => "$('progress').show()",
261  
-              :complete => "$('progress').hide()",
262  
-              :success => "display_item_added(request)",
263  
-              :failure => "display_error(request)"
264  
-            ```
265  
-
266  
-    * **:type** If you want to fire a synchronous request for some obscure reason (blocking the browser while the request is processed and doesn't return a status code), you can use the `:type` option with the value of `:synchronous`.
267  
-
268  
-* Finally, using the `html_options` parameter you can add HTML attributes to the generated tag. It works like the same parameter of the `link_to` helper. There are interesting side effects for the `href` and `onclick` parameters though:
269  
-    * If you specify the `href` parameter, the AJAX link will degrade gracefully, i.e. the link will point to the URL even if JavaScript is disabled in the client browser
270  
-    * `link_to_remote` gains its AJAX behavior by specifying the remote call in the onclick handler of the link. If you supply `html_options[:onclick]` you override the default behavior, so use this with care!
271  
-
272  
-We are finished with `link_to_remote`. I know this is quite a lot to digest for one helper function, but remember, these options are common for all the rest of the Rails view helpers, so we will take a look at the differences / additional parameters in the next sections.
273  
-
274  
-### AJAX Forms
275  
-
276  
-There are three different ways of adding AJAX forms to your view using Rails Prototype helpers. They are slightly different, but striving for the same goal: instead of submitting the form using the standard HTTP request/response cycle, it is submitted asynchronously, thus not reloading the page. These methods are the following:
277  
-
278  
-* `remote_form_for` (and its alias `form_remote_for`) is tied to Rails most tightly of the three since it takes a resource, model or array of resources (in case of a nested resource) as a parameter.
279  
-* `form_remote_tag` AJAXifies the form by serializing and sending its data in the background
280  
-* `submit_to_remote` and `button_to_remote` is more rarely used than the previous two. Rather than creating an AJAX form, you add a button/input
281  
-
282  
-Let's see them in action one by one!
283  
-
284  
-#### `remote_form_for`
285  
-
286  
-#### `form_remote_tag`
287  
-
288  
-#### `submit_to_remote`
289  
-
290  
-### Serving JavaScript
291  
-
292  
-First we'll check out how to send JavaScript to the server manually. You are practically never going to need this, but it's interesting to understand what's going on under the hood.
293  
-
294  
-```ruby
295  
-def javascript_test
296  
-  render :text => "alert('Hello, world!')",
297  
-         :content_type => "text/javascript"
298  
-end
299  
-```
300  
-
301  
-(Note: if you want to test the above method, create a `link_to_remote` with a single parameter - `:url`, pointing to the `javascript_test` action)
302  
-
303  
-What happens here is that by specifying the Content-Type header variable, we instruct the browser to evaluate the text we are sending over (rather than displaying it as plain text, which is the default behavior).
304  
-
305  
-Testing JavaScript
306  
-------------------
307  
-
308  
-JavaScript testing reminds me the definition of the world 'classic' by Mark Twain: "A classic is something that everybody wants to have read and nobody wants to read." It's similar with JavaScript testing: everyone would like to have it, yet it's not done by too much developers as it is tedious, complicated, there is a proliferation of tools and no consensus/accepted best practices, but we will nevertheless take a stab at it:
309  
-
310  
-* (Fire)Watir
311  
-* Selenium
312  
-* Celerity/Culerity
313  
-* Cucumber+Webrat
314  
-* Mention stuff like screw.unit/jsSpec
315  
-
316  
-Note to self: check out the RailsConf JS testing video
392  guides/source/working_with_javascript.md
Source Rendered
... ...
@@ -0,0 +1,392 @@
  1
+Working With JavaScript
  2
+=======================
  3
+
  4
+This guide covers the built-in Ajax/JavaScript functionality of Rails (and
  5
+more); it will enable you to create rich and dynamic AJAX applications with
  6
+ease! We will cover the following topics:
  7
+
  8
+* Quick introduction to AJAX
  9
+* Unobtrusive JavaScript
  10
+* How Rails' built-in helpers assist you
  11
+* Handling AJAX on the server side
  12
+* The Turbolinks gem
  13
+
  14
+-------------------------------------------------------------------------------
  15
+
  16
+An introduction to AJAX
  17
+------------------------
  18
+
  19
+In order to understand AJAX, you must first understand what a web broswer does
  20
+normally.
  21
+
  22
+When you type `http://localhost:3000` into your browser's address bar and hit
  23
+'Go,' the browser (your 'client') makes a request to the server. It parses the
  24
+response, then fetches all associated assets, like JavaScript files,
  25
+stylesheets and images. It then assembles the page. If you click a link, it
  26
+does the same process: fetch the page, fetch the assets, put it all together,
  27
+show you the results. This is called the 'request response cycle.'
  28
+
  29
+JavaScript can also make requests to the server, and parse the response. It
  30
+also has the ability to update information on the page. Combining these two
  31
+powers, a JavaScript writer can make a web page that can update just parts of
  32
+itself, without needing to get the full page data from the server. This is a
  33
+powerful technique that we call AJAX.
  34
+
  35
+Rails ships with CoffeeScript by default, and so the rest of the examples
  36
+in this guide will be in CoffeeScript. All of these lessons, of course, apply
  37
+to vanilla JavaScript as well.
  38
+
  39
+As an example, here's some CoffeeScript code that makes an AJAX request using
  40
+the jQuery library:
  41
+
  42
+```
  43
+$.ajax(url: "/test").done (html) ->
  44
+  $("#results").append html
  45
+```
  46
+
  47
+This code fetches data from "/test", and then appends the result to the `div`
  48
+with an id of `results`.
  49
+
  50
+Rails provides quite a bit of built-in support for building web pages with this
  51
+technique. You rarely have to write this code yourself. The rest of this guide
  52
+will show you how Rails can help you write web sites in this manner, but it's
  53
+all built on top of this fairly simple technique.
  54
+
  55
+Unobtrusive JavaScript
  56
+-------------------------------------
  57
+
  58
+Rails uses a technique called "Unobtrusive JavaScript" to handle attaching
  59
+JavaScript to the DOM. This is generally considered to be a best-practice
  60
+within the frontend community, but you may occasionally read tutorials that
  61
+demonstrate other ways.
  62
+
  63
+Here's the simplest way to write JavaScript. You may see it referred to as
  64
+'inline JavaScript':
  65
+
  66
+```
  67
+<a href="#" onclick="alert('Hello, world.')">Here</a>
  68
+```
  69
+
  70
+When clicked, the alert will trigger. Here's the problem: what happens when
  71
+we have lots of JavaScript we want to execute on a click?
  72
+
  73
+```
  74
+<a href="#" onclick="function fib(n){return n<2?n:fib(n-1)+fib(n-2);};alert('fib of 15 is: ' + fib(15) + '.');">Calculate</a>
  75
+```
  76
+
  77
+Awkward, right? We could pull the function definition out of the click handler,
  78
+and turn it into CoffeeScript:
  79
+
  80
+```
  81
+fib = (n) ->
  82
+  (if n < 2 then n else fib(n - 1) + fib(n - 2))
  83
+```
  84
+
  85
+And then on our page:
  86
+
  87
+```
  88
+<a href="#" onclick="alert('fib of 15 is: ' + fib(15) + '.');">Calculate</a>
  89
+```
  90
+
  91
+That's a little bit better, but what about multiple links that have the same
  92
+effect?
  93
+
  94
+```
  95
+<a href="#" onclick="alert('fib of 16 is: ' + fib(16) + '.');">Calculate</a>
  96
+<a href="#" onclick="alert('fib of 17 is: ' + fib(17) + '.');">Calculate</a>
  97
+<a href="#" onclick="alert('fib of 18 is: ' + fib(18) + '.');">Calculate</a>
  98
+```
  99
+
  100
+Not very DRY, eh? We can fix this by using events instead. We'll add a `data-*`
  101
+attribute to our link, and then bind a handler to the click event of every link
  102
+that has that attribute:
  103
+
  104
+```
  105
+fib = (n) ->
  106
+  (if n < 2 then n else fib(n - 1) + fib(n - 2))
  107
+
  108
+$(document).ready ->
  109
+  $("a[data-fib]").click (e) ->
  110
+    count = $(this).data("fib")
  111
+    alert "fib of #{count} is: #{fib(count)}."
  112
+
  113
+... later ...
  114
+
  115
+<a href="#" data-fib="15">Calculate</a>
  116
+<a href="#" data-fib="16">Calculate</a>
  117
+<a href="#" data-fib="17">Calculate</a>
  118
+```
  119
+
  120
+We call this 'unobtrusive' JavaScript because we're no longer mixing our
  121
+JavaScript into our HTML. We've properly separated our concerns, making future
  122
+change easy. We can easily add behavior to any link by adding the data
  123
+attribute. We can run all of our JavaScript through a minimizer and
  124
+concatenator. We can serve our entire JavaScript bundle on every page, which
  125
+means that it'll get downloaded on the first page load and then be cached on
  126
+every page after that. Lots of little benefits really add up.
  127
+
  128
+The Rails team strongly encourages you to write your CoffeeScript (and
  129
+JavaScript) in this style, and you can expect that many libraries will also
  130
+follow this pattern.
  131
+
  132
+Built-in Helpers
  133
+----------------------
  134
+
  135
+Rails provides a bunch of view helper methods written in Ruby to assist you
  136
+in generating HTML. Sometimes, you want to add a little AJAX to those elements,
  137
+and Rails has got your back in those cases.
  138
+
  139
+Because of Unobtrusive JavaScript, the Rails "AJAX helpers" are actually in two
  140
+parts: the JavaScript half and the Ruby half.
  141
+[rails.js](https://github.com/rails/jquery-ujs/blob/master/src/rails.js)
  142
+provides the JavaScript half, and the regular Ruby view helpers add appropriate
  143
+tags to your DOM. The CoffeeScript in rails.js then listens for these
  144
+attributes, and attaches appropriate handlers.
  145
+
  146
+### form_for
  147
+
  148
+[`form_for`](http://api.rubyonrails.org/classes/ActionView/Helpers/FormHelper.html#method-i-form_for)
  149
+is a helper that assists with writing `<form>`s. `form_for` takes a `:remote`
  150
+option. It works like this:
  151
+
  152
+```
  153
+<%= form_for(@post, remote: true) do |f| %>
  154
+  ...
  155
+<% end %>
  156
+```
  157
+
  158
+This will generate the following HTML:
  159
+
  160
+```
  161
+<form accept-charset="UTF-8" action="/posts" class="new_post" data-remote="true" id="new_post" method="post">
  162
+  ...
  163
+</form>
  164
+```
  165
+
  166
+Note the `data-remote='true'`. Now, the form will be submitted by AJAX rather
  167
+than by the browser's normal submit mechanism.
  168
+
  169
+You probably don't want to just sit there with a filled out `<form>`, though.
  170
+You probably want to do something upon a successful submission. To do that,
  171
+bind to the `ajax:success` event. On failure, use `ajax:error`. Check it out:
  172
+
  173
+```
  174
+<script>
  175
+$(document).ready ->
  176
+  $("#new_post").on("ajax:success", (e, data, status, xhr) ->
  177
+    $("#new_post").append xhr.responseText
  178
+  ).bind "ajax:error", (e, xhr, status, error) ->
  179
+    $("#new_post").append "<p>ERROR</p>"
  180
+</script>
  181
+```
  182
+
  183
+Obviously, you'll want to be a bit more sophisticated than that, but it's a
  184
+start.
  185
+
  186
+### form_tag
  187
+
  188
+[`form_tag`](http://api.rubyonrails.org/classes/ActionView/Helpers/FormTagHelper.html#method-i-form_tag)
  189
+is very similar to `form_for`. It has a `:remote` option that you can use like
  190
+this:
  191
+
  192
+```
  193
+<%= form_tag('/posts', remote: true) %>
  194
+```
  195
+
  196
+Everything else is the same as `form_for`. See its documentation for full
  197
+details.
  198
+
  199
+### link_to
  200
+
  201
+[`link_to`](http://api.rubyonrails.org/classes/ActionView/Helpers/UrlHelper.html#method-i-link_to)
  202
+is a helper that assits with generating links. It has a `:remote` option you
  203
+can use like this:
  204
+
  205
+```
  206
+<%= link_to "first post", @post, remote: true %>
  207
+```
  208
+
  209
+which generates
  210
+
  211
+```
  212
+<a href="/posts/1" data-remote="true">a post</a>
  213
+```
  214
+
  215
+You can bind to the same AJAX events as `form_for`. Here's an example. Let's
  216
+assume that we have a resource `/fib/:n` that calculates the `n`th Fibonacci
  217
+number. We would generate some HTML like this:
  218
+
  219
+<%= link_to "Calculate", "/fib/15", remote: true, data: { fib: 15 } %>
  220
+
  221
+and write some CoffeeScript like this:
  222
+
  223
+```
  224
+$(document).ready ->
  225
+  $("a[data-fib]").on "ajax:success", (e, data, status, xhr) ->
  226
+    count = $(this).data("fib")
  227
+    alert "fib of #{count} is: #{data}."
  228
+```
  229
+
  230
+Easy!
  231
+
  232
+### button_to
  233
+
  234
+[`button_to`](http://api.rubyonrails.org/classes/ActionView/Helpers/UrlHelper.html#method-i-button_to) is a helper that helps you create buttons. It has a `:remote` option that you can call like this:
  235
+
  236
+```
  237
+<%= button_to "A post", @post, remote: true %>
  238
+```
  239
+
  240
+this generates
  241
+
  242
+```
  243
+<form action="/posts/1" class="button_to" data-remote="true" method="post">
  244
+</form>
  245
+```
  246
+
  247
+Since it's just a `<form>`, all of the information on `form_for` also applies.
  248
+
  249
+Server side concerns
  250
+--------------------
  251
+
  252
+AJAX isn't just client-side, you also need to do some work on the server
  253
+side to support it. Often, people like their AJAX requests to return JSON
  254
+rather than HTML. Let's discuss what it takes to make that happen.
  255
+
  256
+### A Simple Example
  257
+
  258
+Imagine you have a series of users that you would like to display and provide a
  259
+form on that same page to create a new user. The index action of your
  260
+controller looks like this:
  261
+
  262
+```
  263
+class UsersController < ApplicationController
  264
+  def index
  265
+    @users = User.all
  266
+    @user = User.new
  267
+  end
  268
+  # ...
  269
+```
  270
+
  271
+The index view (`app/views/users/index.html.erb`) contains:
  272
+
  273
+```
  274
+<b>Users</b>
  275
+
  276
+<ul id="users">
  277
+<% @users.each do |user| %>
  278
+  <%= render user %>
  279
+<% end %>
  280
+</ul>
  281
+
  282
+<br>
  283
+
  284
+<%= form_for(@user, remote: true) do |f| %>
  285
+  <%= f.label :name %><br>
  286
+  <%= f.text_field :name %>
  287
+  <%= f.submit %>
  288
+<% end %>
  289
+```
  290
+
  291
+The `app/views/users/_user.html.erb` partial contains the following:
  292
+
  293
+```
  294
+<li><%= user.name %></li>
  295
+```
  296
+
  297
+The top portion of the index page displays the users. The bottom portion
  298
+provides a form to create a new user.
  299
+
  300
+The bottom form will call the create action on the Users controller. Because
  301
+the form's remote option is set to true, the request will be posted to the
  302
+users controller as an AJAX request, looking for JavaScript. In order to
  303
+service that request, the create action of your controller would look like
  304
+this:
  305
+
  306
+```
  307
+  # app/controllers/users_controller.rb
  308
+  # ......
  309
+  def create
  310
+    @user = User.new(params[:user])
  311
+
  312
+    respond_to do |format|
  313
+      if @user.save
  314
+        format.html { redirect_to @user, notice: 'User was successfully created.' }
  315
+        format.js   {}
  316
+        format.json { render json: @user, status: :created, location: @user }
  317
+      else
  318
+        format.html { render action: "new" }
  319
+        format.json { render json: @user.errors, status: :unprocessable_entity }
  320
+      end
  321
+    end
  322
+  end
  323
+```
  324
+
  325
+Notice the format.js in the respond_to block; that allows the controller to
  326
+respond to your AJAX request. You then have a corresponding
  327
+`app/views/users/create.js.erb` view file that generates the actual JavaScript
  328
+code that will be sent and executed on the client side.
  329
+
  330
+```
  331
+$("<%= escape_javascript(render @user) %>").appendTo("#users");
  332
+```
  333
+
  334
+Turbolinks
  335
+----------
  336
+
  337
+Rails 4 ships with the [Turbolinks gem](https://github.com/rails/turbolinks).
  338
+This gem uses AJAX to speed up page rendering in most applications.
  339
+
  340
+### How Turbolinks works
  341
+
  342
+Turbolinks attaches a click handler to all `<a>` on the page. If your browser
  343
+supports
  344
+[PushState](https://developer.mozilla.org/en-US/docs/DOM/Manipulating_the_browser_history#The_pushState(\).C2.A0method),
  345
+Turbolinks will make an AJAX request for the page, parse the response, and
  346
+replace the entire `<body>` of the page with the `<body>` of the response. It
  347
+will then use PushState to change the URL to the correct one, preserving
  348
+refresh semantics and giving you pretty URLs.
  349
+
  350
+The only thing you have to do to enable Turbolinks is have it in your Gemfile,
  351
+and put `//= require turbolinks` in your CoffeeScript manifest, which is usually
  352
+`app/assets/javascripts/application.js`.
  353
+
  354
+If you want to disable Turbolinks for certain links, add a `data-no-turbolink`
  355
+attribute to the tag:
  356
+
  357
+```
  358
+<a href="..." data-no-turbolink>No turbolinks here</a>.
  359
+```
  360
+
  361
+### Page Change events
  362
+
  363
+When writing CoffeeScript, you'll often want to do some sort of processing upon
  364
+page load. With jQuery, you'd write something like this:
  365
+
  366
+```
  367
+$(document).ready ->
  368
+  alert "page has loaded!"
  369
+```
  370
+
  371
+However, because Turbolinks overrides the normal page loading process, the
  372
+event that this relies on will not be fired. If you have code that looks like
  373
+this, you must change your code to do this instead:
  374
+
  375
+```
  376
+$(document).on "page:change", ->
  377
+  alert "page has loaded!"
  378
+```
  379
+
  380
+For more details, including other events you can bind to, check out [the
  381
+Turbolinks
  382
+README](https://github.com/rails/turbolinks/blob/ec9ca4d6cf9626e03a672f3b9e7968c816aff94e/README.md).
  383
+
  384
+Other resources
  385
+---------------
  386
+
  387
+Here are some helpful links to help you learn even more:
  388
+
  389
+* [jquery-ujs wiki](https://github.com/rails/jquery-ujs/wiki)
  390
+* [jquery-ujs list of external articles](https://github.com/rails/jquery-ujs/wiki/External-articles)
  391
+* [Rails 3 Remote Links and Forms: A Definitive Guide](http://www.alfajango.com/blog/rails-3-remote-links-and-forms/)
  392
+* [Railscasts: Unobtrusive JavaScript](http://railscasts.com/episodes/205-unobtrusive-javascript)

0 notes on commit 4d0c43e

Please sign in to comment.
Something went wrong with that request. Please try again.