Simplified version of my problem:
Here is javascript example called example.html writes the content of a javascript array.
<html>
<head>
<script type="text/JavaScript">
// javascript array called data
data=[
[1,2],[3,4],[5,6]
]
function WriteText(){
for(var i=0;i<3;i++) document.write(data[i],"<br> ")
}
WriteText();
</script>
</head>
</html>
Instead of array the values are written columns file.txt located in the same server directory where the example.html is. file.txt looks like that
1 2
3 4
5 6
I would like to accomplish the same functionality as the example above by reading this file with php and pass it to the javascript. file.txt is a log file where new values are being appended every few seconds So when new values are added I want to see the changes updated to screen. Here is getfile.php function that reads the file.
<?php
$values = array();
foreach(file("file.txt") as $line => $content) {
$values[$line] = explode(' ',$content);
}
echo json_encode($values)
?>
And here is the code that does this.
<html>
<head>
<script type="text/javascript" src="jquery-1.5.2.js"></script>
<script type="text/javascript">
function WriteText(InputData){
for(var i=0;i<InputData.length;i++) document.write(InputData[i],"<br> ")
}
//WriteText(data);
setInterval($.get("getfile.php", { "func": "doSomething" },WriteText , "json"),1000);
</script>
</head>
</html>
I got this idea from http://api.jquery.com/jQuery.get/
This code displays the file.txt. However when I manually append new values to the file.txt there is no update in the browser. If I refresh the page manually the new values are shown as well.
So what am I doing wrong??
Is it the php script or probably I am not using the setInterval() properly.
Thank you.
4 Answers 4
Although I'd recommend looping onSuccess instead of blind polling, the issue is that you haven't created a proper closure for setInterval:
setInterval(function(){
$.get('getFile.php',{},WriteText,'json');
},1000);
3 Comments
Use the Expire header in PHP to tell your browser that the page expires immediately (by passing a date in the past). If you don't, the browser will cache the page.
1 Comment
once the php script finishes looping it stops reading the file.
it doesn't even output anything until php has stopped looking at the file.
the javascript gets no further info from the php script.
to do this you need to use ajax to periodically make a new request for more data and display the new data.
additionally you will need to modify the php to output only the changes, possibly by adding a datetime line
1 Comment
data.push([NewData]) to append the new data entries to the already displayed aray.Do this at the beginning to avoid cache.
$.ajaxSetup ({
// Disable caching of AJAX responses
cache: false
});