Petros Kyriakou
Petros Kyriakou

Reputation: 5343

Ajax loading spinner in Rails 4

I am sending an ajax request in rails and i receive some data for my datatable

The ajax triggering happens using remote: true on a link tag

this is the index.js.erb (the ajax call is made on this)

$('.lessons_table').removeClass('hidden');
$('.lessons').empty();

<% @lessons.each do |l| %>
  $('.lessons').append('<tr>');
  $('.lessons').append('<td><%= l.id %></td>');
  $('.lessons').append('<td><%= best_in_place l, :title, url: "lessons/#{l.id}", cancel_button: 'X' %></td>');
  $('.lessons').append('<td><%= best_in_place l, :duration, url: "lessons/#{l.id}", cancel_button: 'X' %></td>');
  $('.lessons').append('<td><%= best_in_place l, :video, url: "lessons/#{l.id}", cancel_button: 'X' %></td>');
  $('.lessons').append('<td><%= best_in_place l, :course_id, url: "lessons/#{l.id}", cancel_button: 'X' %></td>');
  $('.lessons').append('<td><%= link_to "Remove", admin_course_path(l), method: :delete, data: { confirm: "Are you sure?" }%></td>');
  $('.lessons').append('</tr>');
<% end %>

application.js

$(document).ready(function () {
// hide spinner
  $(".spinner").hide();

  $(document).ajaxStart(function() {
    $(".spinner").show();
  }).ajaxComplete(function() {
      var $loading = $(".spinner");
      setTimeout(function(){
          $loading.hide();
      },1000); //Timeout so you can see the loading happen
  });
});

index.html.erb

<div class="spinner">Loading</div>

what i want is, when i click on the link to retrieve this data, i want a loading text to appear or a css spinner for a specified period of time and when that spinner or text goes away then the data appear.

I played with the code in application.js but its not working properly.

Upvotes: 4

Views: 5749

Answers (1)

Petros Kyriakou
Petros Kyriakou

Reputation: 5343

for future reference this is what actually worked for me,no need for timers and such. it takes as long as the ajax request is not finished.

$(".spinner").hide();

  $(document).ajaxStart(function() {
    $(".spinner").fadeIn('slow');
  }).ajaxStop(function() {
      $(".spinner").hide();
  });

Upvotes: 3

Related Questions