Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Wait for previous AJAX call in FOR loop

How would I wait until the previous ajax call has finished before looping and doing the next call? At the moment the code loops all the way through and executes all the 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>
like image 656
Jake Evans Avatar asked Nov 20 '25 22:11

Jake Evans


1 Answers

You could add the counter (currentIndex) and re-organize the code a little 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();
    });
});
like image 114
sanchez Avatar answered Nov 23 '25 12:11

sanchez



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!