Ajax loading indicator for jQuery ajax requests and asp.net UpdatePanel

Task: Create an ajax loading indicator that will appear every time an ajax request is made using jQuery or the classic asp.net UpdatePanel. See demo

Step 1: Add a div with the loading indicator image on the master page.

    <div id="ProgressIndicator">
        <div>&nbsp;</div> <!-- this will do the vertical align -->
        <img alt="Loading.." src="https://codeutil.files.wordpress.com/2011/11/progressindicator.gif"/>
    </div>

And the css to display the image in the center of the screen.

#ProgressIndicator{
    filter: alpha(opacity=70); 
    -moz-opacity:0.7; 
    opacity: 0.7; 
    width:100%;
    height:100%;
    background-color: #e0dada;
    top: 0px;
    left: 0px;
    z-index: 1000;
    vertical-align:middle;
    text-align:center;    
    position: fixed;
    display: none;
}
#ProgressIndicator div{ 
    display: block;    
    width:48%; height:48%; /* vertical align */
}
#ProgressIndicator img{
    display: block;   
    margin-left: auto;   margin-right: auto; /* horizontal align */
}

Step 2: Add some javascript to show/hide the ProgressIndicator div.

App = {};

App.ProgressIndicator = {
    Show: function () {
        App.ProgressIndicator._changeDisplay('block');
    },

    Hide: function () {
        App.ProgressIndicator._changeDisplay('none');
    },

    _changeDisplay: function (styleDisplay) {
        var progressDiv = $('#ProgressIndicator');
        if (progressDiv.length == 0)
            return;

        progressDiv[0].style.display = styleDisplay;
    }
};

Step 3: Bind the show/hide javascript with the jQuery ajax calls using the events: beforeSend and complete.

        $.ajax({
            url: "CustomService.svc/CustomMethod",
            data: "{}",
            type: "POST",
            processData: false,
            contentType: "application/json; charset=utf-8",
            timeout: 300000,
            dataType: "json",

            beforeSend: function (jqXHR, settings) {
                App.ProgressIndicator.Show();
            },                       
            complete: function (jqXHR, textStatus) {
                App.ProgressIndicator.Hide();
            }
        });

Step 4: Bind the show/hide javascript with all the UpdatePanels. (Note: Add the following code after the ScriptManager element).

 $().ready(function() {
      Sys.WebForms.PageRequestManager.getInstance().add_beginRequest(
                                App.ProgressIndicator.Show);
      Sys.WebForms.PageRequestManager.getInstance().add_endRequest(
                                App.ProgressIndicator.Hide);
});

Test: Try it on the jsFiddle playground 🙂 See demo

Advertisements