Youssef Youssef - 3 months ago 45
Javascript Question

Css changes not working with synchronous ajax call

I want to use

async : false
to make synchronous ajax call for some reasons because i want to wait for every request to complete to execute the next one.

But it doesn't work, the css changes
$(...).css( "opacity" , "1" )
is not working .

But when I switch to
async : true
it works !!

$( ".foo" ).each(function( i , item ) {

$(item ).find(".ajaxLoader").css( "opacity" , "1" );
async : false,
complete : function(){ $(item ).find(".ajaxLoader").css( "opacity" , "0" ); }



The answer is because you lock UI using unrelevant synchronous ajax call just like @epascarello is telling you. Don't use sync requests... You probably don't need any loop anyway because you could get all relevant data from just one ajax call i guess BUT if you want to make some ajax requests (async this time!) sequential, then you can use:

var d = $.Deferred().resolve();
$(".foo").get().forEach(function(foo) {      
  d = d.then(function() {
    return $.ajax({
      /*async: true,*/
      beforeSend: function(){
        $(foo).find(".ajaxLoader").css("opacity", "1");
      complete: function() {
        $(foo).find(".ajaxLoader").css("opacity", "0");