Monday, May 20, 2024
 Popular · Latest · Hot · Upcoming
187
rated 0 times [  193] [ 6]  / answers: 1 / hits: 20389  / 11 Years ago, mon, july 8, 2013, 12:00:00

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.


More From » jquery

 Answers
16

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:





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




[#77143] Friday, July 5, 2013, 11 Years  [reply] [flag answer]
Only authorized users can answer the question. Please sign in first, or register a free account.
leog

Total Points: 225
Total Questions: 113
Total Answers: 118

Location: Oman
Member since Wed, Apr 12, 2023
1 Year ago
;