Search code examples
jqueryajaxloader

I am trying to show a Loader before Jquery Ajax call but it does not work


I am trying to show a div that containers a loader before an ajax call using the following code.

$(document).ajaxStart(function() {
  $("#div_loader").css("display", "block")
})

$(document).ajaxComplete(function() {
  $("#div_loader").css("display", "none");
})

But I am only able to see the div when I debug the JS using Chrome developer Tools. But normally, it never shows up.

Div Html

<div class="loader" id='div_loader'>
            <div class="shade"></div>
            <div class="popup">
            </div>
        </div>

Css for the loader

.loader {
    position: absolute;
    /* height: 100%; */
    max-height: 100%;
    width: 100%;
}

.shade {
    position: fixed;
    z-index: 9999999999;
    top: 0;
    left: 0;
    height: 100%;
    width: 100%;
    background: #333;
    opacity: 0.8;
}

.loader .popup {
    position: fixed;
    height: 102px;
    width: 218px;
    background: url(../images/loader.gif) 50% 85% no-repeat;
    background-size: 32px;
    margin: 12% auto;
    border-radius: 6px;
    top: 10%;
    bottom: 0;
    left: 0;
    right: 0;
    z-index: 99999999999;
}

And here's the ajax request...

function AjaxPostCall(ServicePath, Input) {
    var data = $.parseJSON($.ajax({
        type: "POST",
        contentType: "application/json; charset=utf-8",
        url: ServicePath,
        data: JSON.stringify({ 'Input': Input }),
        dataType: "json",
        async: false
    }).responseText); // This will wait until you get a response from the ajax request.
    var DataSet = JSON.parse(data.d);
    return DataSet;    
}

Solution

  • I have solved it. I was new to Jquery and I didn't know that setting async property of an ajax call to false shall freeze the page up until now. I have tried setting async to true and it's working fine now.