Adam Winster
Adam Winster

Reputation: 69

Display loading icon once while waiting for AJAX call

I'm populating a table with data that automatically updates every 4 seconds using AJAX. I want to display a loading message while waiting for the AJAX to load on the initial page load only.

At the moment I have managed to display the loading message but the message appears every time the data is updated via AJAX (Every 4 seconds) - I want the loading message to only display on the initial page load before the AJAX loads initially. All subsequent AJAX updates should not display the loading message as the table has already been populated with data.

<div id="loading" style="display: none;">Loading..</div>

<script type="text/javascript">
    $(document).ajaxStart(function(){
        $("#loading").show();
        }).ajaxStop(function() {
        $("#loading").hide();
    });
</script>
<script type="text/javascript">
    var auto_refresh = setInterval(
    function () {
        $('#load_onlineusers').load('/online_players.php').fadeIn("slow");
    }, 4000); 
</script>
<div id="load_onlineusers"> </div>

Above is the code that is causing the loading message to display every 4 seconds.

Upvotes: 2

Views: 1520

Answers (1)

Marcelo Vismari
Marcelo Vismari

Reputation: 1179

Use beforeSend method to show loading message and control using a global variable:

var executed = false;
$.ajax({ url: "", 
    type: "", 
    data: "", 
    beforeSend: function() {
        if (!executed) {
            // Show loading
            executed = true;
        }
    },
    complete: function() {
        // Hide loading
    },
    success: function(data) {

    }
});

Upvotes: 1

Related Questions