Reload content from log file on page using AJAX

I run the shell script in the background and redirect the output to a log file in php. I want to display the contents of a log file on a page. I can do this using the following code.

<?php   
    $logfile = "hello";  
?>
function displayOutput()
{
    var html = <?php
        echo filesize($logfile)
            ? json_encode(file_get_contents($logfile))
            : '"Log file is getting generated"'; 
        ?>;
    document.form.text1.value = html;
}

However, the log file continues to be updated until the script completes. How can I reload updated content from a file on the same page?

+3
source share
4 answers

The technique I developed + to discuss here may be useful:

https://web.archive.org/web/20150206001444/http://commavee.com/2007/04/13/ajax-logfile-tailer-viewer/ It has been around for a while + it works well.

+1

n . , - - N ?.

setInterval(displayOutput, (10 * 1000));
// reload log contents every 10 seconds
0

, XMLHttpRequest.

php guy, neiter javascript guru,

function refreshText()
{
    if (window.XMLHttpRequest)
    {
        xhttp = new XMLHttpRequest();
    }
    else // for IE 5/6, just in case
    {
        xhttp = new ActiveXObject("Microsoft.XMLHTTP");
    }
    xhttp.open("GET","/page.php?action=download_log_file", false);
    xhttp.send();

    document.form.text1.value = xhttp.responseXML;
}
setInterval(refreshText, (10 * 1000)); // refresh text1.value every 10 seconds

, jQuery

setInterval(function {
        $.get('/page.php?action=download_log_file', function(data) {
            $('#text1').val(data);
        });
}, (10 * 1000));

script , . http://www.w3schools.com/xml/xml_server.asp

0

COMET-like, . , , - AJAX :

var lines = 0 

function getLog(file, lines) {

    $.ajax({
              type:     'POST',
              url:      'http://thissite.com/getLogFile.php?File=' + file + '&Lines=' + lines,
              dataType: 'json',
              timeout:  400000,
        error:
            function() {
                return false;
            },
        success:
            function(data) {
                if (data.Error) {
                    alert(data.Message)
                } else {
                    if (data.Lines > lines) {
                        // do something with data.LogLines, e.g. add to a textarea
                    }
                    getLogFile(file, data.Lines)
                }
            }
    })
}

script :

  • , , (, ), 1
  • If the number of lines is greater, return new lines and the number of new lines and exit
  • After a number of iterations (I use 100), exit and return the existing row count

The data structure returned by the end of the script is JSON:

{
    Error: // 0 or 1,
    Lines: // Number of lines
    Text: // New lines from log file
}

This works the same as "tail -f" on UNIX, but in the browser!

0
source

Source: https://habr.com/ru/post/1771950/


All Articles