I am a newbie to complicated jQuery scripts, especially AJAX, however I have created a script that polls the sending of a batch of emails to see how many have been sent and when the batch is finished. I cloned pieces of code from different places and added my own mods to create a test site:
http://www.toddcary.com/test/ajax3/index.phpThere are three parts: home page (index.php), the sending script (send_emal.php) and the scrpt that gets the progress (get_progress.php). For this demo of concept, I have a loop that would send 10 emails, but I just have a one second sleep and it writes to a file after each loop that gives the loop number.
My first question is "what halts the jQuery"? When the loop finishes, how is that detected? Is there a process ID that goes away when the loop ends?
And my last question, "is should this work"? The folks on another jQuery forum tell me it should not work and to construct one that does (without telling how/why). Yes, I no doubt could, with effort, construct a background process, but this seems so easy. For other PHP applications, I have used a DB to hold the data (better for multi-user situations).
Here is the AJAX script:
<script type="text/javascript">
$(document).ready(function()
{
// Hide the results
$( "#send_results" ).hide();
//kick off the process
$('#startButton').click(function(event) {
$.ajax({
url: 'send_email.php',
success: function(data) {}
});
//start polling
(function poll(){
setTimeout(function(){
$.ajax({
url: "get_progress.php",
success: function(data){
// Show the results
$( "#send_results" ).show();
//Update the progress
if (data.length > 0) {
$("#send_results").html(data);
} else {
$("#send_results").html("");
}
poll();
},
dataType: "text"
});
$(document).ajaxStop(function(){
$("#send_results").html("Finished");
});
}, 3000);
})(); // Polling
}); //Start button pressed
});
And here is the loop that simulates the sending of emails:
<?php
// Send emails
function save_progress ($fn, $n) {
$handle = fopen($fn, "w+");
if ($handle) {
fwrite($handle, $n);
fclose($handle);
}
}
$count = 0;
$fn = "./tmp/sent.txt";
for ($i = 1; $i <= 10; $i++) {
// Actually, each loop would be sending an email
$count++;
// Save the progress
save_progress($fn, $count);
sleep(1);
}
?>
Thank you,
Todd