Reputation: 21
I want to create a real-time log for my website. A PHP script gets the content from data/log.txt and echoes it. Then the same process gets repeated every second via JavaScript.
I use this code to test it but have a few problems:
<html>
<head>
<title></title>
<script type="text/javascript">
window.onload = startInterval();
function startInterval()
{
setInterval("loadLog();",1000);
}
function loadLog()
{
document.getElementById('log').innerHTML = "<?php
$datei=fopen("data/log.txt","r");
while(!feof($datei))
{
$zeile = fgets($datei,1000);
echo $zeile."<br>";
}
fclose($datei);
?>";
}
</script>
</head>
<body>
Javascript refresh:<br>
<div id="log"></div>
</body>
</html>
Testing PHP seperatly:<br>
<?php
$datei=fopen("data/log.txt","r");
while(!feof($datei))
{
$zeile = fgets($datei,1000);
echo $zeile."<br>";
}
fclose($datei);
?>
The PHP snippet by itself works great. But I can't seem to get the JavaScript part to work...
Problem 1: When I change the content of log.txt the JavaScript part does not refresh itself as I would expect. I'm a beginner with JavaScript so I might have made some obvious mistakes or have a wrong idea how I should do it.
Problem 2:
As long as log.txt consist of only one line the output works:
Javascript refresh: test1
Testing PHP separately: test1
But as soon as I add an even empty line the JavaScript part doesn't load anything.
Upvotes: 0
Views: 572
Reputation: 21
With the help of the comments on my initial question I came up with the following code wich works great:
<html>
<head>
<title></title>
<script src="resources/javascript/jquery-3.3.1.min.js"></script>
<script type="text/javascript">
setInterval(function(){
$('#log').load('loadlog.php');
}, 2000) /* time in milliseconds (ie 2 seconds)*/
</script>
</head>
<body>
Javascript refresh:<br>
<div id="log"></div>
</body>
</html>
Testing PHP seperatly:<br>
<?php
$datei=fopen("data/log.txt","r");
while(!feof($datei))
{
$zeile = fgets($datei,1000);
echo $zeile."<br>";
}
fclose($datei);
?>
Upvotes: 1