Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Show a txt file on a webpage which updates every second

I'm sort of shooting in the dark here; I have no knowledge how to do this so some pointers and/or links to helpful tutorials would be great:

I have a website that I want to display a text file (server log). Probably embedded. The problem is, this file is updated whenever events happen in the server (faster than half a second usually). How can I make it so the webpage displays the file in real time, meaning showing a live feed of the file?

My guess is that it would use javascript and AJAX but my knowledge on both are pretty limited. Any pointers and help would be appreciated :)

like image 211
dukevin Avatar asked Jun 23 '11 07:06

dukevin


2 Answers

My answer uses PHP and Ajax though changing to ASP or any other language wont be hard.
In the head

    <script type="text/javascript">

        function Ajax()
        {
            var
                $http,
                $self = arguments.callee;

            if (window.XMLHttpRequest) {
                $http = new XMLHttpRequest();
            } else if (window.ActiveXObject) {
                try {
                    $http = new ActiveXObject('Msxml2.XMLHTTP');
                } catch(e) {
                    $http = new ActiveXObject('Microsoft.XMLHTTP');
                }
            }

            if ($http) {
                $http.onreadystatechange = function()
                {
                    if (/4|^complete$/.test($http.readyState)) {
                        document.getElementById('ReloadThis').innerHTML = $http.responseText;
                        setTimeout(function(){$self();}, 1000);
                    }
                };
                $http.open('GET', 'loadtxt.php' + '?' + new Date().getTime(), true);
                $http.send(null);
            }

        }

    </script>

In the Body

    <script type="text/javascript">
        setTimeout(function() {Ajax();}, 1000);
    </script>
    <div id="ReloadThis">Default text</div>

</body>

Now using loadtxt.php read the values of the text file

    <?php
        $file = "error.txt";
        $f = fopen($file, "r");
        while ( $line = fgets($f, 1000) ) {
            print $line;
        }
    ?>
like image 185
neo Avatar answered Nov 17 '22 21:11

neo


Using jQuery, you could do the following

setInterval(function() {
    $('#element').load('/url/to/file');
}, 1000);

Would refresh the div with ID element with the file contents every 1 second

like image 8
LeeR Avatar answered Nov 17 '22 21:11

LeeR