Implement a loading indicator for a jQuery AJAX call

devcoder picture devcoder · Aug 14, 2012 · Viewed 301.9k times · Source

I have a Bootstrap modal which is launched from a link. For about 3 seconds it just sits there blank, while the AJAX query fetches the data from the database. How can I implement some sort of a loading indicator? Does twitter bootstrap provide this functionality by default?

EDIT: JS code for modal

<script type="text/javascript">
  $('#myModal').modal('hide');
  $('div.divBox a').click(function(){
    var vendor = $(this).text();
    $('#myModal').off('show');
    $('#myModal').on('show', function(){             
      $.ajax({
        type: "GET",
        url: "ip.php",
        data: "id=" + vendor,
        success: function(html){
          $("#modal-body").html(html);
          $(".modal-header h3").html(vendor);
          $('.countstable1').dataTable({
            "sDom": "T<'row-fluid'<'span6'l><'span6'f>r>t<'row-fluid'<'span6'i><'span6'p>>",
            "sPaginationType": "bootstrap",
            "oLanguage": {
              "sLengthMenu": "_MENU_ records per page"
            },
            "aaSorting":[[0, "desc"]],
            "iDisplayLength": 10,
            "oTableTools": {
              "sSwfPath": "swf/copy_csv_xls_pdf.swf",
              "aButtons": ["csv", "pdf"]
            }
          });
        }
      });
    });
  });
  $('#myModal').on('hide', function () {
    $("#modal-body").empty();
  });
</script>

Answer

leansy picture leansy · Feb 21, 2013

I solved the same problem following this example:

This example uses the jQuery JavaScript library.

First, create an Ajax icon using the AjaxLoad site.
Then add the following to your HTML :

<img src="/images/loading.gif" id="loading-indicator" style="display:none" />

And the following to your CSS file:

#loading-indicator {
  position: absolute;
  left: 10px;
  top: 10px;
}

Lastly, you need to hook into the Ajax events that jQuery provides; one event handler for when the Ajax request begins, and one for when it ends:

$(document).ajaxSend(function(event, request, settings) {
    $('#loading-indicator').show();
});

$(document).ajaxComplete(function(event, request, settings) {
    $('#loading-indicator').hide();
});

This solution is from the following link. How to display an animated icon during Ajax request processing