[javascript] Show loading image while $.ajax is performed

I am just wondering how to show an image that indicates that the async request is running. I use the following code to perform a async request:

$.ajax({
  url: uri,
  cache: false,
  success: function(html){
    $('.info').append(html);
  }
});

Any ideas?

This question is related to javascript jquery css

The answer is


You can, of course, show it before making the request, and hide it after it completes:

$('#loading-image').show();
$.ajax({
      url: uri,
      cache: false,
      success: function(html){
        $('.info').append(html);
      },
      complete: function(){
        $('#loading-image').hide();
      }
    });

I usually prefer the more general solution of binding it to the global ajaxStart and ajaxStop events, that way it shows up for all ajax events:

$('#loading-image').bind('ajaxStart', function(){
    $(this).show();
}).bind('ajaxStop', function(){
    $(this).hide();
});

something like this:

$('#image').show();
$.ajax({
    url: uri,
    cache: false,
    success: function(html){
       $('.info').append(html);
       $('#image').hide();
    }
});

HTML Code :

<div class="ajax-loader">
  <img src="{{ url('guest/images/ajax-loader.gif') }}" class="img-responsive" />
</div>

CSS Code:

.ajax-loader {
  visibility: hidden;
  background-color: rgba(255,255,255,0.7);
  position: absolute;
  z-index: +100 !important;
  width: 100%;
  height:100%;
}

.ajax-loader img {
  position: relative;
  top:50%;
  left:50%;
}

JQUERY Code:

$.ajax({
  type:'POST',
  beforeSend: function(){
    $('.ajax-loader').css("visibility", "visible");
  },
  url:'/quantityPlus',
  data: {
   'productId':p1,
   'quantity':p2,
   'productPrice':p3},
   success:function(data){
     $('#'+p1+'value').text(data.newProductQuantity);
     $('#'+p1+'amount').text("? "+data.productAmount);
     $('#totalUnits').text(data.newNoOfUnits);
     $('#totalAmount').text("? "+data.newTotalAmount);
  },
  complete: function(){
    $('.ajax-loader').css("visibility", "hidden");
  }
});

}

  1. Create a load element for e.g. an element with id = example_load.
  2. Hide it by default by adding style="display:none;".
  3. Now show it using jquery show element function just above your ajax.

    $('#example_load').show(); $.ajax({ type: "POST", data: {}, url: '/url', success: function(){ // Now hide the load element $('#example_load').hide(); } });


_x000D_
_x000D_
**strong text**Set the Time out to the ajax calls_x000D_
function testing(){_x000D_
    _x000D_
    $("#load").css("display", "block");_x000D_
    setTimeout(function(){_x000D_
    $.ajax({_x000D_
             type: "GET",_x000D_
_x000D_
          _x000D_
             url:testing.com,_x000D_
            _x000D_
             async: false,_x000D_
             _x000D_
             success : function(response){_x000D_
           _x000D_
             alert("connection established");_x000D_
_x000D_
              _x000D_
            },_x000D_
            complete: function(){_x000D_
            alert("sended");_x000D_
            $("#load").css("display", "none");_x000D_
         _x000D_
           },_x000D_
            error: function(jqXHR, exception) {_x000D_
                       alert("Write error Message Here");_x000D_
                  },_x000D_
_x000D_
_x000D_
       });_x000D_
     },5000);_x000D_
_x000D_
_x000D_
  }
_x000D_
  .loader {_x000D_
    border: 16px solid #f3f3f3;_x000D_
    border-radius: 50%;_x000D_
    border-top: 16px solid #3498db;_x000D_
    width: 120px;_x000D_
    height: 120px;_x000D_
    -webkit-animation: spin 2s linear infinite; /* Safari */_x000D_
    animation: spin 2s linear infinite;_x000D_
  }_x000D_
  _x000D_
  /* Safari */_x000D_
  @-webkit-keyframes spin {_x000D_
    0% { -webkit-transform: rotate(0deg); }_x000D_
    100% { -webkit-transform: rotate(360deg); }_x000D_
  }_x000D_
  _x000D_
  @keyframes spin {_x000D_
    0% { transform: rotate(0deg); }_x000D_
    100% { transform: rotate(360deg); }_x000D_
  }
_x000D_
<div id="load" style="display: none" class="loader"></div>_x000D_
<input type="button"  onclick="testing()"  value="SUBMIT" >
_x000D_
_x000D_
_x000D_


You can add ajax start and complete event, this is work for when you click on button event

 $(document).bind("ajaxSend", function () {
            $(":button").html('<i class="fa fa-spinner fa-spin"></i> Loading');
            $(":button").attr('disabled', 'disabled');
        }).bind("ajaxComplete", function () {
            $(":button").html('<i class="fa fa-check"></i> Show');
            $(":button").removeAttr('disabled', 'disabled');
        });

Before your call either insert the loading image in a div/span somewhere and then on the success function remove that image. Alternatively you can set up a css class like loading that might look like this

.loading
{
    width: 16px;
    height: 16px;
    background:transparent url('loading.gif') no-repeat 0 0;
    font-size: 0px;
    display: inline-block;
}

And then assign this class to a span/div and clear it in the success function


I've always liked the BlockUI plugin: http://jquery.malsup.com/block/

It allows you to block certain elements of a page, or the entire page while an ajax request is running.


Use the ajax object's beforeSend and complete functions. It's better to show the gif from inside beforeSend so that all the behavior is encapsulated in a single object. Be careful about hiding the gif using the success function. If the request fails, you'll probably still want to hide the gif. To do this use the Complete function. It would look like this:

$.ajax({
    url: uri,
    cache: false,
    beforeSend: function(){
        $('#image').show();
    },
    complete: function(){
        $('#image').hide();
    },
    success: function(html){
       $('.info').append(html);
    }
});

I think this might be better if you have tons of $.ajax calls

$(document).ajaxSend(function(){
    $(AnyElementYouWantToShowOnAjaxSend).fadeIn(250);
});
$(document).ajaxComplete(function(){
    $(AnyElementYouWantToShowOnAjaxSend).fadeOut(250);
});

NOTE:

If you use CSS. The element you want to shown while ajax is fetching data from your back-end code must be like this.

AnyElementYouWantToShowOnAjaxSend {
    position: fixed;
    top: 0;
    left: 0;
    height: 100vh; /* to make it responsive */
    width: 100vw; /* to make it responsive */
    overflow: hidden; /*to remove scrollbars */
    z-index: 99999; /*to make it appear on topmost part of the page */
    display: none; /*to make it visible only on fadeIn() function */
}

The "image" people generally show during an ajax call is an animated gif. Since there is no way to determine the percent complete of the ajax request, the animated gifs used are indeterminate spinners. This is just an image repeating over and over like a ball of circles of varying sizes. A good site to create your own custom indeterminate spinner is http://ajaxload.info/


Examples related to javascript

need to add a class to an element How to make a variable accessible outside a function? Hide Signs that Meteor.js was Used How to create a showdown.js markdown extension Please help me convert this script to a simple image slider Highlight Anchor Links when user manually scrolls? Summing radio input values How to execute an action before close metro app WinJS javascript, for loop defines a dynamic variable name Getting all files in directory with ajax

Examples related to jquery

How to make a variable accessible outside a function? Jquery assiging class to th in a table Please help me convert this script to a simple image slider Highlight Anchor Links when user manually scrolls? Getting all files in directory with ajax Bootstrap 4 multiselect dropdown Cross-Origin Read Blocking (CORB) bootstrap 4 file input doesn't show the file name Jquery AJAX: No 'Access-Control-Allow-Origin' header is present on the requested resource how to remove json object key and value.?

Examples related to css

need to add a class to an element Using Lato fonts in my css (@font-face) Please help me convert this script to a simple image slider Why there is this "clear" class before footer? How to set width of mat-table column in angular? Center content vertically on Vuetify bootstrap 4 file input doesn't show the file name Bootstrap 4: responsive sidebar menu to top navbar Stylesheet not loaded because of MIME-type Force flex item to span full row width