Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Is there a better way to serially submit multiple AJAX requests?

I have a page with multiple forms that I submit via Ajax POSTs serially. At first, I tried using synchronous XHR requests, but this causes the browser to lock up for the duration of the request, and breaks my DOM-manipulation effects, which is unacceptable. So the pattern I ended up using is basically this:

var fcount = 0;    // incremented for each form to be submitted
function submit_form( num ) { 
    var fdata = { ... }; // data from form # num
    $.ajax( { async:    true,
              url:      '/index.cgi',
              data:     fdata,
              type:     'POST',
              success:  function() { 
                  if ( num < fcount ) { 
                      submit_form( ++num );
                  }
              }
           } );
}

$( '#submit_form_btn' ).click( function() { submit_form( 1 ) } );

The recursion strikes me as a bit of an ugly solution to what is essentially an iterative problem. Is there a cleaner or more elegant way that this could be handled?

like image 337
friedo Avatar asked Nov 24 '25 15:11

friedo


2 Answers

Are these requests idempotent? If they are you can simply fire them off one after the other. Otherwise you are somewhat limited by the asynchronous nature of AJAX.

UPDATE

I did some more research and apparently there exists a framework called jQuery Message Queuing that handles serial AJAX requests via message-queuing. Maybe this can help you out.

like image 115
Vivin Paliath Avatar answered Nov 26 '25 03:11

Vivin Paliath


A cleaner way would be to maintain a queue of callbacks(ajax requests) that you want to make and fire them one by one.

like image 36
Mahesh Velaga Avatar answered Nov 26 '25 04:11

Mahesh Velaga



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!