0

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.

1
  • 3
    Have you read the DOC: api.jquery.com/ajaxStart ??? As of jQuery 1.8, the .ajaxStart() method should only be attached to document. Commented May 9, 2014 at 13:16

2 Answers 2

3

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.
        }
    });
Sign up to request clarification or add additional context in comments.

Comments

2

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.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.