2018-07-23 22:29:31 -04:00
**DO NOT READ THIS FILE ON GITHUB, GUIDES ARE PUBLISHED ON https://guides.rubyonrails.org.**
2014-12-23 17:32:50 -05:00
2012-10-23 16:25:21 -04:00
Working with JavaScript in Rails
2012-10-23 16:08:20 -04:00
================================
2012-08-30 22:39:49 -04:00
This guide covers the built-in Ajax/JavaScript functionality of Rails (and
2012-10-23 16:21:02 -04:00
more); it will enable you to create rich and dynamic Ajax applications with
2012-11-29 17:25:02 -05:00
ease!
After reading this guide, you will know:
2012-08-30 22:39:49 -04:00
2012-12-07 12:50:09 -05:00
* The basics of Ajax.
2012-11-29 08:14:08 -05:00
* Unobtrusive JavaScript.
* How Rails' built-in helpers assist you.
2012-12-07 12:50:09 -05:00
* How to handle Ajax on the server side.
2012-11-29 08:14:08 -05:00
* The Turbolinks gem.
2019-07-26 01:54:38 -04:00
* How to include your Cross-Site Request Forgery token in request headers
2012-08-30 22:39:49 -04:00
-------------------------------------------------------------------------------
2012-10-23 16:25:21 -04:00
An Introduction to Ajax
2012-08-30 22:39:49 -04:00
------------------------
2012-10-23 16:21:02 -04:00
In order to understand Ajax, you must first understand what a web browser does
2012-08-30 22:39:49 -04:00
normally.
When you type `http://localhost:3000` into your browser's address bar and hit
2017-08-27 11:34:19 -04:00
'Go', the browser (your 'client') makes a request to the server. It parses the
2012-08-30 22:39:49 -04:00
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,
2017-08-27 11:34:19 -04:00
show you the results. This is called the 'request response cycle'.
2012-08-30 22:39:49 -04:00
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
2012-10-23 16:21:02 -04:00
powerful technique that we call Ajax.
2012-08-30 22:39:49 -04:00
2020-02-20 18:46:01 -05:00
As an example, here's some JavaScript code that makes an Ajax request:
2012-08-30 22:39:49 -04:00
2020-02-20 18:46:01 -05:00
```js
fetch("/test")
.then((data) => data.text())
.then((html) => {
const results = document.querySelector("#results");
results.insertAdjacentHTML("beforeend", data);
});
2012-08-30 22:39:49 -04:00
```
2020-02-21 13:10:34 -05:00
This code fetches data from "/test", and then appends the result to the element
2012-08-30 22:39:49 -04:00
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
2013-01-12 22:37:39 -05:00
will show you how Rails can help you write websites in this way, but it's
2012-08-30 22:39:49 -04:00
all built on top of this fairly simple technique.
Unobtrusive JavaScript
2017-08-27 11:34:19 -04:00
----------------------
2012-08-30 22:39:49 -04:00
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':
2012-10-28 10:26:07 -04:00
```html
2020-02-20 18:46:01 -05:00
< a href = "#" onclick = "this.style.backgroundColor='#990000';event.preventDefault();" > Paint it red< / a >
2012-08-30 22:39:49 -04:00
```
2013-01-05 15:12:39 -05:00
When clicked, the link background will become red. Here's the problem: what
happens when we have lots of JavaScript we want to execute on a click?
2012-08-30 22:39:49 -04:00
2012-10-28 10:26:07 -04:00
```html
2020-02-20 18:46:01 -05:00
< a href = "#" onclick = "this.style.backgroundColor='#009900';this.style.color='#FFFFFF';event.preventDefault();" > Paint it green< / a >
2012-08-30 22:39:49 -04:00
```
Awkward, right? We could pull the function definition out of the click handler,
2020-02-20 18:46:01 -05:00
and turn it a function:
2012-08-30 22:39:49 -04:00
2020-02-20 18:46:01 -05:00
```js
window.paintIt = function(event, backgroundColor, textColor) {
event.preventDefault();
event.target.style.backgroundColor = backgroundColor;
if (textColor) {
event.target.style.color = textColor;
}
}
2012-08-30 22:39:49 -04:00
```
And then on our page:
2012-10-28 10:26:07 -04:00
```html
2020-02-20 18:46:01 -05:00
< a href = "#" onclick = "paintIt(event, '#990000')" > Paint it red< / a >
2012-08-30 22:39:49 -04:00
```
That's a little bit better, but what about multiple links that have the same
effect?
2012-10-28 10:26:07 -04:00
```html
2020-02-20 18:46:01 -05:00
< a href = "#" onclick = "paintIt(event, '#990000')" > Paint it red< / a >
< a href = "#" onclick = "paintIt(event, '#009900', '#FFFFFF')" > Paint it green< / a >
< a href = "#" onclick = "paintIt(event, '#000099', '#FFFFFF')" > Paint it blue< / a >
2012-08-30 22:39:49 -04:00
```
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:
2020-02-20 18:46:01 -05:00
```js
function paintIt(element, backgroundColor, textColor) {
element.style.backgroundColor = backgroundColor;
if (textColor) {
element.style.color = textColor;
}
}
window.addEventListener("load", () => {
const links = document.querySelectorAll(
"a[data-background-color]"
);
links.forEach((element) => {
element.addEventListener("click", (event) => {
event.preventDefault();
const {backgroundColor, textColor} = element.dataset;
paintIt(element, backgroundColor, textColor);
});
});
});
2013-01-05 15:12:39 -05:00
```
```html
< a href = "#" data-background-color = "#990000" > Paint it red< / a >
< a href = "#" data-background-color = "#009900" data-text-color = "#FFFFFF" > Paint it green< / a >
< a href = "#" data-background-color = "#000099" data-text-color = "#FFFFFF" > Paint it blue< / a >
2012-08-30 22:39:49 -04:00
```
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.
Built-in Helpers
2017-08-27 11:34:19 -04:00
----------------
2012-08-30 22:39:49 -04:00
2019-12-21 10:44:51 -05:00
### Remote Elements
2017-04-27 09:13:24 -04:00
2012-08-30 22:39:49 -04:00
Rails provides a bunch of view helper methods written in Ruby to assist you
2012-10-23 16:21:02 -04:00
in generating HTML. Sometimes, you want to add a little Ajax to those elements,
2012-08-30 22:39:49 -04:00
and Rails has got your back in those cases.
2012-10-23 16:21:02 -04:00
Because of Unobtrusive JavaScript, the Rails "Ajax helpers" are actually in two
2012-08-30 22:39:49 -04:00
parts: the JavaScript half and the Ruby half.
2012-11-02 16:26:16 -04:00
2016-02-06 16:41:16 -05:00
Unless you have disabled the Asset Pipeline,
2017-08-01 15:53:17 -04:00
[rails-ujs ](https://github.com/rails/rails/tree/master/actionview/app/assets/javascripts )
2012-08-30 22:39:49 -04:00
provides the JavaScript half, and the regular Ruby view helpers add appropriate
2016-02-06 16:41:16 -05:00
tags to your DOM.
2012-08-30 22:39:49 -04:00
2017-04-27 09:11:36 -04:00
You can read below about the different events that are fired dealing with
remote elements inside your application.
2017-04-27 09:13:24 -04:00
#### form_with
2012-08-30 22:39:49 -04:00
2019-03-05 22:00:45 -05:00
[`form_with` ](https://api.rubyonrails.org/classes/ActionView/Helpers/FormHelper.html#method-i-form_with )
2017-04-27 18:22:21 -04:00
is a helper that assists with writing forms. By default, `form_with` assumes that
your form will be using Ajax. You can opt out of this behavior by
2020-02-20 18:46:01 -05:00
passing the `:local` option to `form_with` .
2012-08-30 22:39:49 -04:00
2012-10-28 10:26:07 -04:00
```erb
2020-02-20 18:46:01 -05:00
< %= form_with(model: @article , id: "new-article") do |form| %>
2012-08-30 22:39:49 -04:00
...
< % end %>
```
This will generate the following HTML:
2012-10-28 10:26:07 -04:00
```html
2020-02-20 18:46:01 -05:00
< form id = "new-article" action = "/articles" accept-charset = "UTF-8" method = "post" data-remote = "true" >
2012-08-30 22:39:49 -04:00
...
< / form >
```
2013-12-14 06:22:04 -05:00
Note the `data-remote="true"` . Now, the form will be submitted by Ajax rather
2012-08-30 22:39:49 -04:00
than by the browser's normal submit mechanism.
You probably don't want to just sit there with a filled out `<form>` , though.
You probably want to do something upon a successful submission. To do that,
bind to the `ajax:success` event. On failure, use `ajax:error` . Check it out:
2020-02-20 18:46:01 -05:00
```js
window.addEventListener("load", () => {
const element = document.querySelector("#new-article");
element.addEventListener("ajax:success", (event) => {
const [_data, _status, xhr] = event.detail;
element.insertAdjacentHTML("beforeend", xhr.responseText);
});
element.addEventListener("ajax:error", () => {
element.insertAdjacentHTML("beforeend", "< p > ERROR< / p > ");
});
});
2012-08-30 22:39:49 -04:00
```
Obviously, you'll want to be a bit more sophisticated than that, but it's a
2017-04-27 11:40:15 -04:00
start.
2012-08-30 22:39:49 -04:00
2017-04-27 09:13:24 -04:00
#### link_to
2012-08-30 22:39:49 -04:00
2019-03-05 22:00:45 -05:00
[`link_to` ](https://api.rubyonrails.org/classes/ActionView/Helpers/UrlHelper.html#method-i-link_to )
2012-10-21 09:49:47 -04:00
is a helper that assists with generating links. It has a `:remote` option you
2012-08-30 22:39:49 -04:00
can use like this:
2012-10-28 10:26:07 -04:00
```erb
2014-05-21 21:47:18 -04:00
< %= link_to "an article", @article , remote: true %>
2012-08-30 22:39:49 -04:00
```
which generates
2012-10-28 10:26:07 -04:00
```html
2014-05-21 21:47:18 -04:00
< a href = "/articles/1" data-remote = "true" > an article< / a >
2012-08-30 22:39:49 -04:00
```
2017-04-27 14:32:50 -04:00
You can bind to the same Ajax events as `form_with` . Here's an example. Let's
2014-05-21 21:47:18 -04:00
assume that we have a list of articles that can be deleted with just one
2013-01-05 15:12:39 -05:00
click. We would generate some HTML like this:
2012-08-30 22:39:49 -04:00
2012-10-28 10:26:07 -04:00
```erb
2014-05-21 21:47:18 -04:00
< %= link_to "Delete article", @article , remote: true, method: :delete %>
2012-10-28 10:15:35 -04:00
```
2012-08-30 22:39:49 -04:00
2020-02-20 18:46:01 -05:00
and write some JavaScript like this:
2012-08-30 22:39:49 -04:00
2020-02-20 18:46:01 -05:00
```js
window.addEventListener("load", () => {
const links = document.querySelectorAll("a[data-remote]");
links.forEach((element) => {
element.addEventListener("ajax:success", () => {
alert("The article was deleted.");
});
});
});
2012-08-30 22:39:49 -04:00
```
2017-04-27 09:13:24 -04:00
#### button_to
2012-08-30 22:39:49 -04:00
2019-03-05 22:00:45 -05:00
[`button_to` ](https://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:
2012-08-30 22:39:49 -04:00
2012-10-28 10:26:07 -04:00
```erb
2014-05-21 21:47:18 -04:00
< %= button_to "An article", @article , remote: true %>
2012-08-30 22:39:49 -04:00
```
this generates
2012-10-28 10:26:07 -04:00
```html
2014-05-21 21:47:18 -04:00
< form action = "/articles/1" class = "button_to" data-remote = "true" method = "post" >
2015-08-02 06:11:23 -04:00
< input type = "submit" value = "An article" / >
2012-08-30 22:39:49 -04:00
< / form >
```
2017-04-27 14:32:50 -04:00
Since it's just a `<form>` , all of the information on `form_with` also applies.
2012-08-30 22:39:49 -04:00
2019-12-21 10:44:51 -05:00
### Customize Remote Elements
2017-04-27 11:40:15 -04:00
It is possible to customize the behavior of elements with a `data-remote`
2017-05-21 05:29:09 -04:00
attribute without writing a line of JavaScript. You can specify extra `data-`
2017-04-27 11:40:15 -04:00
attributes to accomplish this.
#### `data-method`
Activating hyperlinks always results in an HTTP GET request. However, if your
2017-08-22 20:36:38 -04:00
application is [RESTful ](https://en.wikipedia.org/wiki/Representational_State_Transfer ),
2017-04-27 18:22:21 -04:00
some links are in fact actions that change data on the server, and must be
2017-04-27 11:40:15 -04:00
performed with non-GET requests. This attribute allows marking up such links
with an explicit method such as "post", "put" or "delete".
The way it works is that, when the link is activated, it constructs a hidden form
in the document with the "action" attribute corresponding to "href" value of the
2017-04-27 18:22:21 -04:00
link, and the method corresponding to `data-method` value, and submits that form.
2017-04-27 11:40:15 -04:00
NOTE: Because submitting forms with HTTP methods other than GET and POST isn't
widely supported across browsers, all other HTTP methods are actually sent over
POST with the intended method indicated in the `_method` parameter. Rails
automatically detects and compensates for this.
#### `data-url` and `data-params`
2017-04-27 18:22:21 -04:00
Certain elements of your page aren't actually referring to any URL, but you may want
them to trigger Ajax calls. Specifying the `data-url` attribute along with
2017-04-27 11:40:15 -04:00
the `data-remote` one will trigger an Ajax call to the given URL. You can also
specify extra parameters through the `data-params` attribute.
This can be useful to trigger an action on check-boxes for instance:
```html
< input type = "checkbox" data-remote = "true"
data-url="/update" data-params="id=10" data-method="put">
```
#### `data-type`
2017-04-27 18:22:21 -04:00
It is also possible to define the Ajax `dataType` explicitly while performing
requests for `data-remote` elements, by way of the `data-type` attribute.
2017-04-27 11:40:15 -04:00
### Confirmations
You can ask for an extra confirmation of the user by adding a `data-confirm`
2020-02-20 18:46:01 -05:00
attribute on links and forms. The user will be presented with a JavaScript `confirm()`
2017-04-27 11:40:15 -04:00
dialog containing the attribute's text. If the user chooses to cancel, the action
doesn't take place.
2017-04-27 18:22:21 -04:00
Adding this attribute on links will trigger the dialog on click, and adding it
2017-04-27 11:40:15 -04:00
on forms will trigger it on submit. For example:
```erb
< %= link_to "Dangerous zone", dangerous_zone_path,
2017-04-27 14:32:50 -04:00
data: { confirm: 'Are you sure?' } %>
2017-04-27 11:40:15 -04:00
```
This generates:
```html
< a href = "..." data-confirm = "Are you sure?" > Dangerous zone< / a >
```
The attribute is also allowed on form submit buttons. This allows you to customize
the warning message depending on the button which was activated. In this case,
you should **not** have `data-confirm` on the form itself.
The default confirmation uses a JavaScript confirm dialog, but you can customize
2017-04-27 18:22:21 -04:00
this by listening to the `confirm` event, which is fired just before the confirmation
window appears to the user. To cancel this default confirmation, have the confirm
2020-02-20 18:46:01 -05:00
handler return `false` .
2017-04-27 11:40:15 -04:00
### Automatic disabling
It is also possible to automatically disable an input while the form is submitting
by using the `data-disable-with` attribute. This is to prevent accidental
double-clicks from the user, which could result in duplicate HTTP requests that
2017-04-27 18:22:21 -04:00
the backend may not detect as such. The value of the attribute is the text that will
2017-04-27 11:40:15 -04:00
become the new value of the button in its disabled state.
This also works for links with `data-method` attribute.
For example:
```erb
2020-02-20 18:46:01 -05:00
< %= form_with(model: Article.new) do |form| %>
2019-11-01 15:08:49 -04:00
< %= form.submit data: { disable_with: "Saving..." } %>
2020-02-20 18:46:01 -05:00
< % end %>
2017-04-27 11:40:15 -04:00
```
This generates a form with:
```html
< input data-disable-with = "Saving..." type = "submit" >
```
2017-06-13 01:37:03 -04:00
### Rails-ujs event handlers
Rails 5.1 introduced rails-ujs and dropped jQuery as a dependency.
As a result the Unobtrusive JavaScript (UJS) driver has been rewritten to operate without jQuery.
These introductions cause small changes to `custom events` fired during the request:
2017-09-18 02:38:47 -04:00
NOTE: Signature of calls to UJS's event handlers has changed.
2017-06-20 11:20:36 -04:00
Unlike the version with jQuery, all custom events return only one parameter: `event` .
In this parameter, there is an additional attribute `detail` which contains an array of extra parameters.
2020-02-20 18:46:01 -05:00
For information about the previously used `jquery-ujs` in Rails 5 and earlier, read the [`jquery-ujs` wiki ](https://github.com/rails/jquery-ujs/wiki/ajax ).
2017-06-13 01:37:03 -04:00
| Event name | Extra parameters (event.detail) | Fired |
|---------------------|---------------------------------|-------------------------------------------------------------|
| `ajax:before` | | Before the whole ajax business. |
| `ajax:beforeSend` | [xhr, options] | Before the request is sent. |
| `ajax:send` | [xhr] | When the request is sent. |
| `ajax:stopped` | | When the request is stopped. |
| `ajax:success` | [response, status, xhr] | After completion, if the response was a success. |
| `ajax:error` | [response, status, xhr] | After completion, if the response was an error. |
| `ajax:complete` | [xhr, status] | After the request has been completed, no matter the outcome.|
Example usage:
2020-02-20 18:46:01 -05:00
```js
document.body.addEventListener("ajax:success", (event) => {
const [data, status, xhr] = event.detail;
});
2017-06-13 01:37:03 -04:00
```
2017-10-13 09:05:12 -04:00
### Stoppable events
2020-02-20 18:46:01 -05:00
2018-04-14 11:56:34 -04:00
You can stop execution of the Ajax request by running `event.preventDefault()`
from the handlers methods `ajax:before` or `ajax:beforeSend` .
The `ajax:before` event can manipulate form data before serialization and the
2017-10-13 09:05:12 -04:00
`ajax:beforeSend` event is useful for adding custom request headers.
2017-10-13 09:05:12 -04:00
If you stop the `ajax:aborted:file` event, the default behavior of allowing the
browser to submit the form via normal means (i.e. non-Ajax submission) will be
canceled and the form will not be submitted at all. This is useful for
implementing your own Ajax file upload workaround.
2020-02-20 18:46:01 -05:00
Note, you should use `return false` to prevent an event for `jquery-ujs` and
`event.preventDefault()` for `rails-ujs` .
2018-04-14 11:56:34 -04:00
2012-10-23 16:25:21 -04:00
Server-Side Concerns
2012-08-30 22:39:49 -04:00
--------------------
2012-10-23 16:21:02 -04:00
Ajax isn't just client-side, you also need to do some work on the server
side to support it. Often, people like their Ajax requests to return JSON
2012-08-30 22:39:49 -04:00
rather than HTML. Let's discuss what it takes to make that happen.
### A Simple Example
Imagine you have a series of users that you would like to display and provide a
form on that same page to create a new user. The index action of your
controller looks like this:
2012-10-28 10:26:07 -04:00
```ruby
2012-08-30 22:39:49 -04:00
class UsersController < ApplicationController
def index
@users = User.all
@user = User.new
end
# ...
```
The index view (`app/views/users/index.html.erb`) contains:
2012-10-28 10:26:07 -04:00
```erb
2012-08-30 22:39:49 -04:00
< b > Users< / b >
< ul id = "users" >
2013-06-17 04:21:59 -04:00
< %= render @users %>
2012-08-30 22:39:49 -04:00
< / ul >
< br >
2019-11-01 15:08:49 -04:00
< %= form_with model: @user do |form| %>
< %= form.label :name %>< br >
< %= form.text_field :name %>
< %= form.submit %>
2012-08-30 22:39:49 -04:00
< % end %>
```
The `app/views/users/_user.html.erb` partial contains the following:
2012-10-28 10:26:07 -04:00
```erb
2012-08-30 22:39:49 -04:00
< li > < %= user.name %>< / li >
```
The top portion of the index page displays the users. The bottom portion
provides a form to create a new user.
2013-12-14 06:22:04 -05:00
The bottom form will call the `create` action on the `UsersController` . Because
2012-08-30 22:39:49 -04:00
the form's remote option is set to true, the request will be posted to the
2013-12-14 06:22:04 -05:00
`UsersController` as an Ajax request, looking for JavaScript. In order to
serve that request, the `create` action of your controller would look like
2012-08-30 22:39:49 -04:00
this:
2012-10-28 10:26:07 -04:00
```ruby
2012-08-30 22:39:49 -04:00
# app/controllers/users_controller.rb
# ......
def create
@user = User.new(params[:user])
respond_to do |format|
if @user .save
format.html { redirect_to @user , notice: 'User was successfully created.' }
2016-05-10 12:34:12 -04:00
format.js
2012-08-30 22:39:49 -04:00
format.json { render json: @user , status: :created, location: @user }
else
format.html { render action: "new" }
format.json { render json: @user .errors, status: :unprocessable_entity }
end
end
end
```
2017-04-16 22:24:38 -04:00
Notice the `format.js` in the `respond_to` block: that allows the controller to
2012-10-23 16:21:02 -04:00
respond to your Ajax request. You then have a corresponding
2012-08-30 22:39:49 -04:00
`app/views/users/create.js.erb` view file that generates the actual JavaScript
code that will be sent and executed on the client side.
2020-02-20 18:46:01 -05:00
```js
var users = document.querySelector("#users");
users.insertAdjacentHTML("beforeend", "< %= j render(@user) %>");
2012-08-30 22:39:49 -04:00
```
2020-02-20 18:46:01 -05:00
NOTE: JavaScript view rendering doesn't do any preprocessing, so you shouldn't use ES6 syntax here.
2012-08-30 22:39:49 -04:00
Turbolinks
----------
2016-02-23 18:56:42 -05:00
Rails ships with the [Turbolinks library ](https://github.com/turbolinks/turbolinks ),
which uses Ajax to speed up page rendering in most applications.
2012-08-30 22:39:49 -04:00
2012-10-23 16:25:21 -04:00
### How Turbolinks Works
2012-08-30 22:39:49 -04:00
2017-04-16 22:24:38 -04:00
Turbolinks attaches a click handler to all `<a>` tags on the page. If your browser
2012-08-30 22:39:49 -04:00
supports
2015-08-11 11:33:55 -04:00
[PushState ](https://developer.mozilla.org/en-US/docs/Web/Guide/API/DOM/Manipulating_the_browser_history#The_pushState%28%29_method ),
2012-10-23 16:21:02 -04:00
Turbolinks will make an Ajax request for the page, parse the response, and
2012-08-30 22:39:49 -04:00
replace the entire `<body>` of the page with the `<body>` of the response. It
will then use PushState to change the URL to the correct one, preserving
refresh semantics and giving you pretty URLs.
2016-02-23 18:56:42 -05:00
If you want to disable Turbolinks for certain links, add a `data-turbolinks="false"`
2012-08-30 22:39:49 -04:00
attribute to the tag:
2012-10-28 10:26:07 -04:00
```html
2016-02-23 18:56:42 -05:00
< a href = "..." data-turbolinks = "false" > No turbolinks here< / a > .
2012-08-30 22:39:49 -04:00
```
2012-10-23 16:25:21 -04:00
### Page Change Events
2012-08-30 22:39:49 -04:00
2020-02-20 18:46:01 -05:00
You'll often want to do some sort of processing upon
page load. Using the DOM, you'd write something like this:
2012-08-30 22:39:49 -04:00
2020-02-20 18:46:01 -05:00
```js
window.addEventListener("load", () => {
alert("page has loaded!");
});
2012-08-30 22:39:49 -04:00
```
However, because Turbolinks overrides the normal page loading process, the
2017-04-16 22:25:23 -04:00
event that this relies upon will not be fired. If you have code that looks like
2012-08-30 22:39:49 -04:00
this, you must change your code to do this instead:
2020-02-20 18:46:01 -05:00
```js
document.addEventListener("turbolinks:load", () => {
alert("page has loaded!");
});
2012-08-30 22:39:49 -04:00
```
For more details, including other events you can bind to, check out [the
Turbolinks
2016-02-07 20:17:31 -05:00
README](https://github.com/turbolinks/turbolinks/blob/master/README.md).
2012-08-30 22:39:49 -04:00
2019-07-26 01:54:38 -04:00
Cross-Site Request Forgery (CSRF) token in Ajax
----
When using another library to make Ajax calls, it is necessary to add
the security token as a default header for Ajax calls in your library. To get
the token:
2020-02-20 18:46:01 -05:00
```js
const token = document.getElementsByName(
"csrf-token"
)[0].content;
2019-07-26 01:54:38 -04:00
```
2019-07-29 06:41:35 -04:00
You can then submit this token as a `X-CSRF-Token` header for your
Ajax request. You do not need to add a CSRF token for GET requests,
only non-GET ones.
2019-07-26 01:54:38 -04:00
2020-02-20 18:46:01 -05:00
You can read more about about Cross-Site Request Forgery in the [Security guide ](https://guides.rubyonrails.org/security.html#cross-site-request-forgery-csrf ).
2019-07-26 01:54:38 -04:00
2012-10-23 16:25:21 -04:00
Other Resources
2012-08-30 22:39:49 -04:00
---------------
Here are some helpful links to help you learn even more:
2020-02-20 18:46:01 -05:00
* [rails-ujs wiki ](https://github.com/rails/rails/tree/master/actionview/app/assets/javascripts )
2012-08-30 22:39:49 -04:00
* [Railscasts: Unobtrusive JavaScript ](http://railscasts.com/episodes/205-unobtrusive-javascript )
2013-05-28 08:19:22 -04:00
* [Railscasts: Turbolinks ](http://railscasts.com/episodes/390-turbolinks )