I am using jQuery to call a function when a button is clicked. This function that is being called is in PHP and returns logging information. I have tried to use setInterval() but it calls the function at whatever rate I choose and tends to return duplicate logging information and most of the time it freezes. Is there a way that I can make repeated calls to a PHP function from jQuery, but only call the function after the last call is finished and returned?
Here is the jQuery code that makes involves the setInterval()
setInterval(
function(){
$.getJSON("ajax.php?function=tail&pointer=" + ftell,
function(data){
var obj = [];
obj = $.parseJSON(data);
ftell = obj[0];
$("#tail").append(obj[1]);
});
}, 2000);
Here is the PHP function that it calls
function tail(){
$file = "/path/to/the/log/file.log";
$handle = fopen($file, "r");
clearstatcache();
$currentSize = filesize($file);
$offset = $_REQUEST['pointer'] - $currentSize;
if ($_REQUEST['pointer'] == 0) {
fseek($handle, -1024, SEEK_END);
} else {
fseek($handle, $_REQUEST['pointer'], SEEK_END);
}
while ($buffer = fgets($handle)) {
$log .= $buffer . "<br />";
}
fclose($handle);
$results = array('0' => $currentSize, '1' => str_replace('"', '\"', $log));
echo json_encode($results);
}
This will trigger another ajax event five seconds after the first one has finished. It wont matter whether it’s succeeded or failed.
Some concerns with writing code like this can be that it doesn’t contain a mechanism for cancelling.