Wait ajax to complete before continue loop

Question

I’m developing a code that searches for about 5000 orphaned users, and delete them. Using Ajax, how do I wait for a response to complete and then continue the loop?
Currently, the loop will keep executing and I have pending ajax call in the background that I think will hammer the server to process it at the same time.

Here is the sample code.

<script>
        var users_info = <?php echo json_encode($usersarray); ?>;
        console.log(users_info);
        $=jQuery;
        var each = '';
        j = 0;
        for ( i=0; i < users_info.length; i++) {
            each = users_info[i];
            var data = {
                'action': 'delete_orphan_users',
                'user_id': each
            };
            $.post(ajaxurl, data, function(response) {
                $("#status").prepend(response);
                j++;
                $("#deletedusers").html(j);
            });
            if (j==users_info.length){
                alert('Finished');
            }
        }

    </script>
0
, , sharulhafiz 4 years 2018-12-30T00:09:19-05:00 0 Answers 87 views 0

Leave an answer

Browse
Browse