Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to chain ajax requests?

I have to interact with a remote api that forces me to chain requests. Thats a callback-hell in asynchronous mode:

// pseudocode: ajax(request_object, callback) ajax(a, function() {   ajax(b(a.somedata), function() {     ajax(c(b.somedata), function() {       c.finish()     }   })  }) 

It would be much more readable in sync mode:

sjax(a) sjax(b(a.somedata)) sjax(c(b.somedata)) c.finish() 

But Sjax is evil :) How do I do that in a nice not-so-evil and readable way?

like image 223
defnull Avatar asked Jun 15 '09 11:06

defnull


People also ask

How do I handle multiple AJAX requests?

The jQuery library provides a way to make any callback function waiting for multiple Ajax calls. This method is based on an object called Deferred. A Deferred object can register callback functions based on whether the Deferrred object is resolved or rejected. Here is an example of the Deferred object.

Can you nested AJAX calls?

There is a requirement to make multiple AJAX calls parallelly to fetch the required data and each successive call depends on the data fetched in its prior call. Since AJAX is asynchronous, one cannot control the order of the calls to be executed.

What happens when one AJAX call is still running and you send an another AJAX call before the data of first AJAX call comes back?

Since Ajax calls are asynchronous, the application will not 'pause' until an ajax call is complete, and simply start the next call immediately. JQuery offers a handler that is called when the call is successful, and another one if an error occurs during the call.


2 Answers

You could have a single function which is passed an integer to state what step the request is in, then use a switch statement to figure out what request needs to be make next:

function ajaxQueue(step) {   switch(step) {     case 0: $.ajax({               type: "GET",               url: "/some/service",               complete: function() { ajaxQueue(1); }      }); break;     case 1: $.ajax({               type: "GET",               url: "/some/service",               complete: function() { ajaxQueue(2); }             }); break;     case 2: $.ajax({               type: "GET",               url: "/some/service",               complete: function() { alert('Done!'); }             }); break;   } }  ajaxQueue(0); 

Hope that helps!

like image 109
Jamie Rumbelow Avatar answered Sep 26 '22 08:09

Jamie Rumbelow


Don't use anonymous functions. Give them names. I don't know if you're able to do what I wrote below though:

var step_3 = function() {     c.finish(); };  var step_2 = function(c, b) {     ajax(c(b.somedata), step_3); };  var step_1 = function(b, a) {   ajax(b(a.somedata), step_2); };  ajax(a, step_1); 
like image 39
Ionuț G. Stan Avatar answered Sep 26 '22 08:09

Ionuț G. Stan