llanato
llanato

Reputation: 2491

jQuery Ajax loading image not loading on ajax call

I'm using the below jQuery snippet for an ajax loading image which I use on numerous sites, for some reason it wont disply the loading image when an ajax request is fired.

jQuery:

$(".loading").hide().ajaxStart(function() {
    $(this).show();
}).ajaxStop(function() {
    $(this).hide();
});

Example Ajax call (working as expected and returning correct data):

$('#list').change(function() {
    var vCID = 1;

    if ($.trim(vCID) && vCID != 0)
    {
        var vData = {aid:1001,id:vCID};

        $.ajax(
        {
            url : "ajax.php",
            type: "POST",
            data : vData,
            success: function(data, textStatus, jqXHR)
            {
                $('#itemList').html(data);
            }
        });
    }
});

HTML:

<div class="loading">&nbsp;</div>

CSS:

.loading {
    width: 40px;
    height: 40px;
    margin: 10px auto 0 auto;
    background: url('images/loading.gif') no-repeat;
}

The HTML code is being affected by the jQuery as display: none is being added on page load, there are no errors and if I change display: block on the HTML via firebug the loading.gif image shows up.

Any help greatly appreciated.

Upvotes: 0

Views: 3759

Answers (2)

Jai
Jai

Reputation: 74738

you can make it with beforeSend and complete methods:

     $.ajax({
        url: "ajax.php",
        type: "POST",
        data: vData,
        beforeSend: function () {
            $(".loading").show();  // <----show before sending
        },
        success: function (data, textStatus, jqXHR) {
            $('#itemList').html(data);
        },
        complete: function () {
            $(".loading").hide(); // on complete of ajax hide it.
        }
    });

Upvotes: 3

Tom Hallam
Tom Hallam

Reputation: 1950

Perhaps try changing it to

$(".loading").hide();

$(document).ajaxStart(function() {
    $(".loading").show();
}).ajaxStop(function() {
    $(".loading").hide();
});

Instead of chaining it to $('.loading') which may not fire an ajaxStart() event.

Upvotes: 2

Related Questions