Wait for the previous AJAX call in the FOR loop
How do I wait until the previous ajax call has completed before the loop and the next call? At this point, the code goes all the way and executes all ajax requests at once!
<script>
var busy;
function check(mailpass, proxy){
var post_data = {};
var post_json = "";
post_data['mailpass'] = mailpass;
post_data['proxy'] = '108.36.248.67:17786';
post_json = JSON.stringify(post_data);
jQuery.ajax({
url: '/postdata' ,
type: "POST",
data: {params: post_json},
success: function(data){
var obj = JSON.parse(data);
if(obj.error == 0){
//
$("#acc-live").append(obj.msg + "<br/>");
} else if(obj.error == 1){
//
$("#socks-die").append(obj.msg+ "<br/>");
} else if(obj.error == 2){
//
$("#acc-die").append(obj.msg+ "<br/>");
}
}
});
}
$(document).ready(function(){
$("#submit").click(function(){
var lines = $("#lines").val().split('\n');
for(var i = 0;i < lines.length;i++){
check(lines[i], '123');
}
});
});
</script>
+3
source to share
3 answers
You can add a counter (currentIndex) and arrange your code a bit.
var busy;
var lines;
var currentIndex = 0;
function checkNext(){
if( currentIndex >= lines.length ){
console.log('all done');
return;
}
var mailpass = lines[currentIndex];
var proxy = '123';
var post_data = {};
var post_json = "";
post_data['mailpass'] = mailpass;
post_data['proxy'] = '108.36.248.67:17786';
post_json = JSON.stringify(post_data);
jQuery.ajax({
url: '/postdata' ,
type: "POST",
data: {params: post_json},
success: function(data){
var obj = JSON.parse(data);
if(obj.error == 0){
//
$("#acc-live").append(obj.msg + "<br/>");
} else if(obj.error == 1){
//
$("#socks-die").append(obj.msg+ "<br/>");
} else if(obj.error == 2){
//
$("#acc-die").append(obj.msg+ "<br/>");
}
currentIndex++; //Increase the counter
checkNext();
}
});
}
$(document).ready(function(){
$("#submit").click(function(){
lines = $("#lines").val().split('\n');
checkNext();
});
});
+3
source to share
You should look at jQuery.when ():
http://api.jquery.com/jquery.when/
This will continue until the async calls complete to continue
0
source to share
If you just want to wait for the ajax call to complete, why can't you just make it async : false
? (although I would not recommend it)
jQuery.ajax({
url: '/postdata' ,
type: "POST",
async : false, // here
data: {params: post_json},
success: function(data){
var obj = JSON.parse(data);
if(obj.error == 0){
//
$("#acc-live").append(obj.msg + "<br/>");
} else if(obj.error == 1){
//
$("#socks-die").append(obj.msg+ "<br/>");
} else if(obj.error == 2){
//
$("#acc-die").append(obj.msg+ "<br/>");
}
}
});
which will make the loop wait for the method to complete its execution
0
source to share