Sabinov Musia Sabinov Musia - 1 month ago 9
Ajax Question

How to function with ajax calls asynchronously and display loader until done?

how can I call ajax request or any function simple in new thread?

I know about

async: false
but my code has this structure:

1.user click on some item, and this fire click event

2.in event I call this function

var myData= {};
$.ajax({
type: "GET",
url: "...",
contentType: "application/json; charset=utf-8",
async: false,
cache: false,
dataType: "json",
success: function (s0) {
myData.s0= s0;


$.ajax({
type: "GET",
url: "sss",
contentType: "application/json; charset=utf-8",
async: false,
cache: false,
dataType: "json",
success: function (s1) {
myData.s1 = s1;

$.ajax({
type: "GET",
url: "...",
contentType: "application/json; charset=utf-8",
async: false,
cache: false,
dataType: "json",
success: function (s2) {
myData.s2= s2;
}
});
}
});
}
});

// I need call this function when all ajax are done.
myFunc(myData);


My current code works but causes the web freezes until data are not downloaded beaouse I have
asyn: false
but I do not know how to solve it asynchronously

Optimal solution for me is call this freezing and display loading gif until done.

Answer

Well there is no fix for UI freeze during a synchronous AJAX so you might want to try web workers but it has its own caveat .I would suggest you to use jquery promise so that you don't need to define separate success ,error callbacks .A promise is guaranteed to yield so at the end of chain either you will have values in myData or not but it won't hangup forever

//show loader
$.ajax({
        type: "GET",
        url: "...",
        contentType: "application/json; charset=utf-8",
        async: false,
        cache: false,
        dataType: "json",
}).then(function( s0, textStatus, jqXHR ){ 
         myData.s0= s0;
         return  $.ajax( {
         type: "GET",
         url: "sss",
         async: false,
         cache: false,
         dataType: "json"} );
 }).then(function( s1, textStatus, jqXHR ) { 
          myData.s1 = s1;
          $.ajax( {
          type: "GET",
          url: "...",
          async: false,
          cache: false,
          dataType: "json"});  
}).then(function( s2, textStatus, jqXHR ) {
          myData.s2= s2;
          //hide loader
})

Read more