jQuery addClass() not running before jQuery.ajax()

Posted by Josh on Stack Overflow See other posts from Stack Overflow or by Josh
Published on 2010-03-31T14:01:02Z Indexed on 2010/03/31 14:03 UTC
Read the original article Hit count: 303

Filed under:
|
|

I'm trying to have a button that onclick will apply a class loading (sets cursor to "wait") to the body, before making a series of ajax requests.

Code is:

$('#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've tried doing

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

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

In firebug I can see that body doesn't get the loading class until after the requests are complete.

Any ideas?

© Stack Overflow or respective owner

Related posts about jQuery

Related posts about addclass