ZedZim ZedZim - 26 days ago 11
CSS Question

Showing a loading div during a jQuery ajax call

Im trying to show a loading div while waiting for an ajax call to complete. I have tried a couple of methods but cant seem to get anything to work consistently.

with my current code it works if i have a break point on the function that shows the div once the ajax is complete.

Fiddle



var https = 'https://www.googleapis.com/calendar/v3/calendars/';

function HideCheckShowLoading(checkId) {
$("#check_" + checkId).hide('slow', function() {
$("#loading_" + checkId).show('slow');
});
};

function HideLoadingShowCheck(checkId) {
$("#loading_" + checkId).finish().hide('slow', function() {
$("#check_" + checkId).finish().show('slow');
});
};
$(document).ready(function() {
$('#get').click(function() {
HideCheckShowLoading(1);
$.ajax({
url: https,
dataType: 'jsonp',
type: "GET",
success: function(response) {
//do something
},
error: function() {
//do something else
}
}).done(function() {
HideLoadingShowCheck(1)
});

});
$('#get2').click(function() {
HideLoadingShowCheck(1);
});

});

#check_1
{
background-color:red;
}

#loading_1
{
background-color:blue;
}

<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script>
<div id="check_1">Check</div>
<div hidden id="loading_1">LOADING</div>
<button id="get">Get</button>
<button id="get2">Get2</button>





What i would like to happen is,


  1. on the click of a button we hide the check div

  2. we show the loading div

  3. make the ajax call

  4. if successful do something(Reload the contents of the check div)

  5. hide the loading div

  6. show the check div



As said I have tried a few methods that i have found but i repeatedly get stuck with just the loading div shown

Thanks

Answer

I believe you may be slightly over-complicating things here. Something simple like this would suffice:

$('#get').click(function() {
    HideCheckShowLoading();
    $.ajax({
       url: https,
       dataType: 'jsonp',
       type: "GET",
       success: function (response) {
           //do something
       },
       error: function() {
           //do something else                
       },
       complete: HideLoadingShowCheck
   });
});

If you don't want the HideLoadingShowCheck routine to happen after success or error (standard behavior of complete), you can just move a function call HideLoadingShowCheck(); into your success and error blocks instead of using complete.