【Rails4】【Ajax】インジケータを表示させる

環境

Rails 4.1.8
jQuery

目的

  • Ajax通信中にインジケータ(グルグル)を表示させて、通信終了後に非表示にする。
  • インジケータ表示中はモーダルの様に半透明のレイヤーを被せて、ボタン押下等ができないようにする

1. インジケータ(グルグル)のgif画像をDLし、assets/images/に配置
今回はこちらから
Ajaxload - Ajax loading gif generator

こちらも有名
Loader Generator - Ajax loader

2. Viewにインジケータとフォームを記述

# 今回はインジケータの下に「Loading…」と表示させる
<body>
  <div id="loading">
    <div id="sending-msg"><%= 'Loading…' %></div>
  </div>
  <%= form_for @sample, :url => {action: 'sample'}, :html => {class: 'ajax-load'}, remote: true do |f| %>
    <%= f.submit('Submit') %>
  <% end %>
</body>

3. CSS

/* インジケータを背景に表示。サイズを100%にすることでモーダルになる。 */
/* 背景色と透過率は好みで */
#loading {
  width: 100%;
  height: 100%;
  z-index: 9999;
  position: fixed;
  top: 0;
  left: 0;
  background-color: #f7f7f9;
  filter: alpha(opacity=65);
  -moz-opacity: 0.65;
  -khtml-opacity: 0.65;
  opacity: 0.65;
  background-image: url('../assets/ajax-loader.gif');
  background-position: center center;
  background-repeat: no-repeat;
  background-attachment: fixed;
  display: none;
}
/* 画像下の文字の表示 */
#sending-msg {
  text-align: center;
  padding-top: 26%;
  color: #000;
  font-weight: bold;
}

4. Javascript(Coffeescript)

/* 2でフォームにajax-loadクラスをつけたので、そのAjaxの送信前、送信完了後にインジケータ制御 */
$ ->
  $(document).on("ajax:before", ".ajax-load", (event) ->
    $('#loading').show() # インジケータ表示
  ).on("ajax:complete", ".ajax-load", (event) ->
    $('#loading').hide() # インジケータ非表示
  )