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 Answer 1

1

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

Sign up to request clarification or add additional context in comments.

3 Comments

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.
json_encode returns a js string when you pass it a php string like that (I tested it just now)
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?

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.