0

I want to display a loading icon via CSS on my page when a user sends data via ajax, and then remove this loading icon once the ajax call is complete. The page successfully shows the icon once, but not again without a page refresh. However, the ajax call is being completed successfully for multiple calls. Here is my code:

Relevant Html:

<head>
<link rel="stylesheet" href="~/Content/Loading.css" type="text/css&quot; id="loading_gif"/>
</head>
...
...
<button type="button" class="btn btn-success" id="button">Import</button>
...
...
<div class="modal"><!-- Placed at bottom of page --></div>

Ajax:

$(document).ready(function () {
    $('#button').click(function () {                        
        $.ajax({
            type: "POST",
            url: '@Url.Action("Submit")',
            data: { 
              //submit data via jQuery 
            },
            dataType: 'json',
            beforeSend: function() {
                $body.addClass("loading");                        
            },
            success: function (data) {                        
                //render a partialView                    
            },
            complete: function () {
                $body.removeClass("loading");
            }
        });                
    });
}(jQuery));

CSS:

.modal {
  display: none;
  position: fixed;
  z-index: 1000;
  top: 0;
  left: 0;
  height: 100%;
  width: 100%;
  background: rgba( 128, 128, 128, .5 ) url('../img/ajax-loader-bar.gif') 50% 50% no-repeat;
}

/* When the body has the loading class, we turn
the scrollbar off with overflow:hidden */
body.loading {
  overflow: hidden;
}

/* Anytime the body has the loading class, our
modal element will be visible */
body.loading .modal {
  display: block;
}
Mike Cluck
  • 28,921
  • 12
  • 72
  • 85
William
  • 135
  • 2
  • 15
  • 1
    `#button` is dynamically replaced? Is the ID unique? Try `$(document).on('click', '#button', function() {` – Tushar Mar 22 '16 at 15:42
  • 1
    Your `$(document).ready()` setup is incorrect. You're **calling** the "ready" handler. Remove the `(jQuery)` from the end. – Pointy Mar 22 '16 at 15:43

1 Answers1

1

Global setup for ajax calls

Have a look at this answer: https://stackoverflow.com/a/2387709/3298029

Here is a fiddle where the loading class is added and removed: http://jsfiddle.net/0fpdud5h/

jQuery.ajaxSetup({
  beforeSend: function() {
     body.addClass('loading');
  },
  complete: function(){
     body.removeClass('loading');
  },
  success: function() {}
});

It triggers multiple times on this fiddle. Hope this gets you started.

Community
  • 1
  • 1
d.h.
  • 1,158
  • 1
  • 17
  • 31