trying_hal9000
trying_hal9000

Reputation: 4403

AJAX w/ rails and using ajaxStart and ajaxStop

I'm using rails to handle ajax requests for change between menu tabs on my homepage. I tried adding in a new function to hide and show a ajax spinner depending on when ajaxStart and ajaxStop is called, I can't seem to get it working. If this because I'm making ajax calls through rails and shown below? How can I get this going? Thanks a lot for any help.

application.js

$(function() {
  $('#loading').ajaxStart(function() {
    $(this).show();
  }).ajaxComplete(function() {
    $(this).hide();
  });
});

Users controller

def bookmarks
 @bookmarks = ...
 respond_with @bookmarks
end

Views/users/bookmarks.js.erb

$('#stream').html('<%= escape_javascript(render("posts", :posts => @bookmarks)) %>');

layout

<body>
...
<div id="loading">
  <p><img src="images/ajax-loader.gif" /> Please Wait</p>
</div>
</body>

css

#loading { 
     display:none;
     position:fixed;
     left:0;
     top:0;
     width:100%;
     height:100%;
     background:black;
 }

Upvotes: 1

Views: 1137

Answers (1)

Brandon J. Boone
Brandon J. Boone

Reputation: 16472

I've never used rails so I don't understand/see where your ajax call is happening. That said, your syntax for ajaxStart and ajaxComplete looks fine to me.

Here's a working example using jQuery's typical ajax function (which I assume rails is using under the hood if you're expecting ajaxStart and ajaxComplete to work.

JSFiddle:

http://jsfiddle.net/MNd5h/1/

HTML

<div id="loading">
  <p>Please Wait</p>
</div>

JavaScript

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

$.ajax({
    url: "/echo/json/"
});

CSS

#loading { 
     display:none;
     position:fixed;
     left:0;
     top:0;
     width:100%;
     height:100%;
 }

Upvotes: 0

Related Questions