views:

40

answers:

1

I have a page where onclick on a button displays the text content from the file in the text area on the page

javascript function

function displayOutput()
    {
    <?php   
        $logfile = "hello";  
        $fh = fopen($logfile, 'r');  
        $size = filesize($logfile);  
        if($size == 0)  
                {  
            echo "Log file is getting generated";  
                }  
        else{  
            $theData = fread($fh, $size);  
            $data = trim($theData);  
            }  
        fclose($fh);  
    ?>  
    var html = "<?php echo $data; ?>";  
    document.form.text1.value = html;  
}  

Using this function i am able to correctly display the file contents only if the file contains a single line.

I want to display multiple lines in the textarea. I tried removing $data = trim($theData) but then no output is seen. If i echo $theData i am able to see all the file contents but in a single line. I also tried using while(!feof(filename)) but even that didn't work.

How do i display all the contents of the file on a new line using javascript?

+1  A: 

Try this:

<?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;
}

edited to include the filesize=0 condition

cambraca
This looks like basically what you want, but since you are setting the text directly, you will not want to `json_encode();` the output. You will want to wrap it in a string though, and it might be necessary to escape any string characters in the file contents.
Andy Groff
`json_encode` returns a js string when you pass it a php string like that (I tested it just now)
cambraca
Thanks...it works!!
Neha
i also want to reload the file everytime i click the button. Since it is a log file, new contents are added. Can i do that?
Neha