Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Synchronous Ajax with jQuery

Tags:

jquery

ajax

I have a web app that makes a ton of $.post() requests. The server must receive these in the order that they were created. To guarantee this, I first thought I'd make my own queue that dequeued and fired the next Ajax call after the previous one had completed.

Then I saw there's an async:false option with the you can use with $.ajax().

I've changed all my requests to use $.ajax({ async: false, ... }), but when I monitor them in Firebug, requests are not sent one-by-one, each next request being fired off after the last has received a response.

What is async suppose to do then? How might I pipe my Ajax so that one executes at a time, the next one firing when the last one has completed (received response)?

like image 246
AgileMeansDoAsLittleAsPossible Avatar asked May 20 '26 01:05

AgileMeansDoAsLittleAsPossible


1 Answers

Instead of using async:false, you could create a function that is called recursively from the callback.

function sendReq( arr ) {
    var current = arr.shift(); // Remove the first item from the Array.
    $.ajax({
        url: current.url,      // Use the url from the first item.
        success: function( dat ) {
            current.func( dat );  // Call the function of the first item.
            if( arr.length )      // If there are items left in the Array,
               sendReq( arr );    //     make a recursive call, sending
        }                         //     the remainder of the array.
    });
}

// Ordered collection of requests to be made.
var req_set = [
    {url:'someurl', func:function( dat ) { /*do something with dat*/ }},
    {url:'anotherurl', func:function( dat ) { /*do something with dat*/ }},
    {url:'someother', func:function( dat ) { /*do something with dat*/ }}
];
 // Start the first call, sending the entire set.
sendReq( req_set );

So basically:

  • Make an array of objects that contain the needed elements for the requests.
  • Make a function that accepts the array.
  • The function removes the first item from the Array, and uses that object to populate the request properties.
  • In the callback, after the function for that item has been called, make a recursive call to the function, passing the remainder of the Array.
  • This will continue the recursive calls until the Array is empty.
like image 151
user113716 Avatar answered May 22 '26 09:05

user113716



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!