Queue multiple AJAX requests, waiting for response and not freezing browser?

ajax, javascript, jquery, queue

Solution

Set async to false if you want to wait for a response (default: true)

$.ajax({
    async: false,
    ...

http://api.jquery.com/jQuery.ajax/

If you do not want blocking, you can set a success handler function using `.ajaxComplete()`, and you have to keep track of active AJAX connections if you want to wait for all to complete - How to know when all ajax calls are complete

The best solution would be to minimize the number of AJAX requests to one. If you have to make a loop of AJAX requests, the logic could be simplified somewhere (put that in the server perhaps?)

EDIT 1: (In response to OP edit)

If you want to queue the AJAX requests, this question has been answered before here:

- Sequencing ajax requests

- Queue ajax requests using jQuery.queue()

You could also use these libraries (all you needed to do was Google):

- https://code.google.com/p/jquery-ajaxq/

- http://codecanyon.net/item/ajax-queue-jquery/full_screen_preview/4903957

- http://schneimi.wordpress.com/2008/03/10/multiple-ajax-requests-problems-and-ajaxqueue-as-solution/

Problem

I am working a script, I need to loop an array of AJAX requests: ``` $('#fetchPosts').click(function(){ for(var i=0; i < link_array.length; i++) { settings = { // some object not relevant } var status = main_ajaxCall(settings, i); // ajax call } }); function main_ajaxCall(settings, i) { $.ajax({ type: "POST", url: "../model/insert.php", data:{obj_settings: settings}, dataType: "json", cache: false, success: function (data) { // some handeling here return 0; }, error: function(XMLHttpRequest, textStatus, errorThrown) { return 1; }, }; ``` Why does the AJAX requests fire instantly? It does not seem to wait for a response from model/insert.php, is there any way to force it to wait for a response before firing the next AJAX request? EDIT 1: It seems I wasnt clear, sorry, I dont want it to wait, I want to queue up the calls. I cant make the call in one request, this is impossible in my current situation.

Original source

Related problems