JQuery addClass () doesn't work until jQuery.ajax ()

I am trying to create a button in which onclick will apply a class loading(sets the cursor to "wait") in the body before making a series of ajax requests.

The code:

$('#addSelected').click(function(){
    $('body').addClass('loading');

    var products = $(':checkbox[id^=add_]:checked');
    products.each(function(){
        var prodID = $(this).attr('id').replace('add_', '');
        var qty = $('#qty_' + prodID).val();
        if($('#prep_' + prodID).val())
        {
            prodID += ':' + $('#prep_' + prodID).val();
        }
        // Have to use .ajax rather than .get so we can use async:false, otherwise
        // product adds happen in parallel, causing data to be lost. 
        $.ajax({
            url: '<?=base_url()?>basket/update/' + prodID + '/' + qty,
            async: false,
            beforeSend: function(){
                $('body').addClass('loading');
            }
        });
    });
});

I tried to do

$('body').addClass('loading');

both before requests and as beforeSend callback, but there is no difference.

In firebug, I see that the bodyclass does not receive loadinguntil the requests are complete.

Any ideas?


I did not sort it the way I consider clean, but I found a solution.

If I add setTimeout(function(){above var products...and }, 1);at the end of the block products.each, this fragment will linger, so addClass will happen first.

+3
source share
2 answers

. jQuery ajaxStart.

.

$('#addSelected').ajaxStart(function() {
  $('body').addClass('loading');
});

EDIT: jquery , async = false . jquery:

asyncBoolean : true

(.. true). , false. , , , .

, ? ajaxStart , .

+2

jQuery ? , ajax. v1.4.2 jQuery, , , - ?

, - , "each()", addClass .ajax.

0

Source: https://habr.com/ru/post/1739311/


All Articles