Nothing
Nothing

Reputation: 2642

Use loading image before the content success loading in jquery

I used JSON to retrieve data from my controller and print it on my view using jquery. The content is display when users click on the menu link. Before the content load, user have to wait a few second.

So in this period, I want to display the loading image in my view, and when the content is display success, the loading image hide.

This is the html that I put the loading image :

<div id="loading" style="position:relative; text-align:center;">  
   <img src="/Content/Images/loading.gif" alt="Processing" />
</div>

This is the sample function of jquery :

function ViewProduct() {
  $('#loading').hide();
  $("#content ul#navmenu-v").empty();
  $.getJSON(url, function (data) {
     $.each(data, function (index, dataOption) {
     var new_li = $("<li class='level1' id='select_list'><a href='javascript:void(0);' id='" + dataOption.ID + "' class ='selectedcategory'>" + dataOption.Name + "</a>");
        mainMenu.append(new_li);
        $('a#' + dataOption.ID).click(function () {
            //display the loading image
            $.getJSON("ProductListing/Index", data, function (product) {
                //append the content in the body of web page
            });
        });
    });
});

}

This is where I called the function :

$(document).ready(function () {
   ViewProduct();
});

Question : I want to hide the loading image after click. Anyone can tell me about this? Thanks so much.

Upvotes: 2

Views: 6135

Answers (1)

Maros
Maros

Reputation: 1973

$.getJSON(url, [, data], [, callback]) is shorthand for

$.ajax({
  url: url,
  dataType: 'json',
  data: data,
  success: callback
});

The jQuery.ajax specification shows that we can specify a callback that will fire whether or not the AJAX request succeeds. We will use it to hide the loading icon after the request:

function ViewProduct() {
    $('#loading').hide();
    $("#content ul#navmenu-v").empty();

    $.getJSON(url, function (data) {
        $.each(data, function (index, dataOption) {
        var new_li = $("<li class='level1' id='select_list'><a href='javascript:void(0);' id='" + dataOption.ID + "' class ='selectedcategory'>" + dataOption.Name + "</a>");
        mainMenu.append(new_li);
        $('a#' + dataOption.ID).click(function () {

            //display the loading image
            $('#loading').show();

            $.ajax({
                'type': 'GET',
                'url': 'ProductListing/Index',
                'data': data,
                'dataType': 'json',
                'success': function (product) {
                    //append the content in the body of web page
                },
                'complete': function () {
                    $('#loading').hide();
                }
            });
        });
    });
});

Upvotes: 2

Related Questions