Lykos Lykos - 3 months ago 39
Ajax Question

jQuery - Show loading symbol when changing option from dropdown

I'm having the following select menu:

<select name="period" id="stats-period">
<option value="all">All time</option>
<option value="360">12 months</option>
<option value="270">9 months</option>
<option value="180">6 months</option>
<option value="90">3 months</option>
<option selected="selected" value="30">30 days</option>
<option value="7">7 days</option>
</select>


When I select an option from the dropdown I do an ajax call in order to get the correct records from database, so this is my script:

function timePeriod(changePeriod) {

var url = '<?= admin_url('reports/change_period') ?>';

$.post(url, {period: changePeriod}, function (response) {

var json = $.parseJSON(response);

if (json.error == true) {
$('#reports').hide();
$('#no-reports').show();
}
else {
$('#reports').show();
$('#no-reports').hide();

$('#numprojects').text(json.projects);
$('#average-cost').text(json.average_cost.toFixed(2));
$('#over-budget').text(json.over_budget);
$('#average-client-flags').text(json.average_client_flags);
$('#average-delayed').text(json.average_delayed.toFixed(1));
}
});
}

$('#stats-period').on('change', function(){
var selected = $(this).val();
timePeriod(selected);
});


What I wan't to do is to show a loading symbol when changing the selected value of the dropdown, until the ajax call is completed, How can I do this?

Answer

Assuming your loading gif is inside a div with ID = #myDiv

function timePeriod(changePeriod) {

    var url = '<?= admin_url('reports/change_period') ?>';

    $('#myDiv').show();

    $.post(url, {period: changePeriod}, function (response) {

        $('#myDiv').hide();

        var json = $.parseJSON(response);

        >SNIP<