Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

jQuery synchronous non-blocking ajax calls

In my web application, I have a series of ajax calls that are fired rapidly. On the server, these need to be processed in the same order as they are sent from the client.

I have been using the async: false configuration in jQuery to do this. However this causes the GUI to become very sluggish while it blocks for calls to finish. With async: true the GUI is responsive, but the requests are not always processed in order.

Is there an alternative non-blocking way to queue up ajax requests, so the next one is sent only after the previous one has finished?

NOTE: I don't have a "list" of requests to process. The requests are generated on the fly, so I need to be able to stuff them into some sort of a FIFO queue when they are generated, then consume the queue with some process.

like image 886
bradvido Avatar asked Jul 24 '12 21:07

bradvido


People also ask

Can AJAX requests be made synchronous?

AJAX can access the server both synchronously and asynchronously: Synchronously, in which the script stops and waits for the server to send back a reply before continuing. Asynchronously, in which the script allows the page to continue to be processed and handles the reply if and when it arrives.

How do you make AJAX call synchronously?

Synchronous AJAX call is made when async setting of jQuery AJAX function is set to false while Asynchronous AJAX call is made when async setting of jQuery AJAX function is set to true. Default value of the async setting of jQuery AJAX function is true.

Is an AJAX call synchronous or asynchronous?

Ajax requests are Asynchronous by nature, but it can be set to Synchronous , thus, having the codes before it, execute first.

What is synchronous AJAX request?

Synchronous AJAX is a process that makes a java script to halt or stop the processing an application until a result is sent by a server. The browser is frozen, while the request is processed. The response time is 99.99% quick and fast enough.


1 Answers

It can be done easily with jQuery promises:

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

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

firstAjax().pipe(secondAjax).pipe(...).done(function() {
    alert('all requests have successfully finished');
});

or

$.when(firstAjax()).pipe(secondAjax).pipe(...).done(function() {
    alert('all requests have successfully finished');
});

http://jsfiddle.net/zerkms/WQcVD/1/

like image 172
zerkms Avatar answered Sep 23 '22 06:09

zerkms