Spring
Spring

Reputation: 11865

jQuery manage multi Ajax calls results

I have a settings page on my jQuery mobile website When user clicks save button, I update the server for 3 different user inputs i.e language, currency, threshold

In order to do this I make 3 separate ajax calls (with PUT). So when all are succesfull I go to another page if any of those fails I stay on the same page and show the error messages.

The problem is I only want to switch the page if all calls are succesful, and if there are any errors I want to show one alert with all messages (rather than 3 separete alert windows), so I need to wait the results of all these calls.

To achive this in all 3 Ajax calls I used;

async:false 

And I put a boolean in all these calls succes methods like;

     success: function (data){
           languageUpatesuccesful=true;

        }

and then something like this;

 if(languageUpatesuccesful){
   make the next call to update currency..etc
}

...

if(allsuccesful(){
  changepage();
}

So I can track when exactly when one calls finishes then I make the next call, if all succesful switch to another page.

While this works, I think this is a horrible solution, is there a way to achive this by using async:true ?

Because disabling asynchrous ajac freezes the page and I cant even show animations, also it is not recommended by jQuery. But then how can I know when these 3 calls are finished and take action depending on result?

Upvotes: 2

Views: 1560

Answers (3)

Bergi
Bergi

Reputation: 665527

You can easily chain them by using the Deferred interface:

$.ajax({…})
  .then(function(languageUpateResult) {
     return $.ajax({…});
  })
  .then(function(currencyUpdateResult) {
     return $.ajax({…});
  })
  .then(function(thresholdUpdateResult) {
     changePage();
  });

Sorry, I skipped the fact that the ajax calls are separate. The above code executes them sequentially, if you just want to execute them in parallel and wait for all of them to finish use $.when() - see @FelixKling's answer.

Upvotes: 4

Felix Kling
Felix Kling

Reputation: 817198

Use deferred objects together with $.when:

$.when(ajax1(), ajax2(), ajax3()).done(function() {
    // all Ajax calls successful, yay! 
}).fail(function() {
    // oh noes, at least one call failed!
});

Where ajaxX is defined as:

function ajax1() {
    return $.ajax(...);
}

If you indeed want to chain the Ajax calls instead of having them concurrent, have a look at Bergi's solution.

Upvotes: 8

mako-taco
mako-taco

Reputation: 732

You can try using web workers to do your async calls in a background thread. Web workers have pretty good browser support and should solve your issue. If you are interested, I have written a little abstraction of the web worker library to make them easier to work with (just send me a pm).

Upvotes: 1

Related Questions