Lamloumi Afif
Lamloumi Afif

Reputation: 9081

Synchronous XMLHttpRequest in WebApi 2

I have a webApi 2 application. I used Ajax several time in this way async:false , because sometimes

The statement I am calling has to be complete before the next statement in my function can be called

I get a browser warning then

Synchronous XMLHttpRequest on the main thread is deprecated because of its detrimental effects to the end user's experience.

I understand that calling a web service synchronisly can make problems such as a long waiting, browser crush ... etc. But I need to get the result before continuing the next statement.

I need to know

  1. How can I avoid this warning and amke the call asynchrous?
  2. Why Synchronous XMLHttpRequest on the main thread is deprecated? what is the meaning of this statement?

Upvotes: 0

Views: 65

Answers (1)

user405398
user405398

Reputation:

You could move your sync call to a web worker. But again, you will make it async.

Its better to make the current sync call to server as async call.

Example(pseudo sync call code):

var dataFromServer = makeSyncCallToServer();
//use dataFromServer

Example(pseudo async call code):

makeAsyncCallToServer(function(dataFromServer) {
  //use dataFromServer here
});

If you want to make multiple calls to server, then async comes handy here.

For example, you could use async.series

async.series([yourAsnycFunctionOne, yourAsnycFunctionTwo, yourAsnycFunctionThree], finalFunctionToCall)

So yourAsnycFunctionOne, yourAsnycFunctionTwo, yourAsnycFunctionThree will be called in series and finalFunctionToCall will be called in the end of the series.

In your case, you could do something like:

function getCustomerList(callback) {
   //make the async http call and call "callback" with the customer data
}
function postFormDataToServer(formdata, callback) {
  //send form data server and call "callback" after successful post
}
function hideGrid() {}
function hideForm() {}
function showForm() {}
function showGrid() {}
$('#add-button').on('click', function() {
  showForm();
  hideGrid();
});
$('#form-id').on('submit', function(e) {
  e.preventDefault();
  var formdata = {/**populate form data**/};
  hideForm();
  postFormDataToServer(formdata, function() {
    getCustomerList(function(customerList) {
      //populate grid with new data
      showGrid();
    });
  });
});

Upvotes: 1

Related Questions