Background
I have made a PHP script that sends an email to many users by looping through the users' ID via POST. When I try using the script with a lot of users (1000+), the script times out.
To resolve this, I decided to use AJAX on the front end that sends each request individually. I have set up a simple sample page to test my code. The PHP script delays for five seconds. I would expect to get a request per five seconds. However, I am getting a delay of five seconds, and then all of the responses at once. With more research, I discovered that my AJAX calls are chaining, which is not what I want. Rather, I would only like to send the next request when the last AJAX call was completed.
Code
HTML
<form id='frmAjax' method='post' action='run_form.php'>
<span>1</span><input type="checkbox" name='option' value='test1'><br>
<span>2</span><input type="checkbox" name='option' value='test2'><br>
<span>3</span><input type="checkbox" name='option' value='test3'><br>
<span>4</span><input type="checkbox" name='option' value='test4'><br>
<span>5</span><input type="checkbox" name='option' value='test5'><br>
<span>6</span><input type="checkbox" name='option' value='test6'><br>
<span>7</span><input type="checkbox" name='option' value='test7'><br>
<span>8</span><input type="checkbox" name='option' value='test8'><br>
<span>9</span><input type="checkbox" name='option' value='test9'><br>
<input id='btnAjax' type='button' value='Submit AJAX'>
</form>
Javascript Code
$("#btnAjax").click(function() {
var options = $("#frmAjax input:checkbox:checked");
$(options).each(function(i) {
var postData = {option: $(options[i]).val()};
$.ajax({
type: "POST",
data: postData,
url: "run_ajax.php",
success: function(result) {
console.log(result);
},
statusCode: {
500: function() {
console.log("Error");
}
}
});
});
});
PHP Code
<?
echo("Success on ".$_POST["option"].".");
sleep(5);
?>
Question
My question is this, how can I make my AJAX calls recursive, not sending the next request until the previous has finished?