Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

JavaScript loading image freezes while making ajax call

Tags:

jquery

loading

I've built a page using jQuery that uses an async Ajax call. I'm trying to display a loading gif but for the life of me I can't get it to work. The gif never displays. Any ideas?

function updateCityList(state) {
        $("#city-loading").empty().html('<img src="/Images/loading.gif" />');
        $.ajax(
            {
                type: "GET",
                async: true,
                url: "/NPA/GetCities/" + state,
                dataType: "json",
                success: function(optionData) {
                    var options = [];
                    $(optionData).each(function(index, optionData) {
                        if ($('#cities option[value=' + optionData.Value + ']').length == 0)
                            options.push(optionData);
                    });
                    $("#cityList").fillSelect(options);
                }
            });
        $("#city-loading").empty();
    };
like image 546
user135498 Avatar asked Jun 10 '26 12:06

user135498


1 Answers

Your call to $.ajax() sets off the request and then immediately continues, because you're doing the call asynchronously. Hence the call to $("#city-loading").empty(); happens immediately.

You need to move the $("#city-loading").empty(); to the end of the success: function, so that it doesn't get called until the AJAX request completes.

like image 124
RichieHindle Avatar answered Jun 12 '26 06:06

RichieHindle



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!