Anil
Anil

Reputation: 49

How to display Text file on clicking button in html

I have four text files and I want to display it on the browser using the buttons I want to create four buttons when click on the 1st button first text should open. Please help me out from this I'm new to HTML and PHP.

Upvotes: 2

Views: 9879

Answers (2)

Mayank Pandeyz
Mayank Pandeyz

Reputation: 26288

It seems that you dont need to necessarily read the file on the triggered action of clicking a button. If you are already reading the file, load it into a hidden HTML element, like a <div>, then use Javascript to show that on the click of the button.

PHP:

$myFile = "file.txt";
    $fh = fopen($myFile, 'r');
    $theData = fread($fh, filesize($myFile));
    fclose($fh);
    echo '<div id="hidden_content" style="display:none">'.$theData.'</div>';

HTML Link:

<a href="#" onclick="show_content()">Show it!</a>

Javascript:

function show_content(){
    document.getElementByID('hidden_content').style.display = 'block';
}

Or you can read the data dynamically using the ajax and show it on the page.

Upvotes: 1

Manthan Dave
Manthan Dave

Reputation: 2147

To do this you need to read about php file functions.

Refer this link - http://php.net/manual/en/function.file.php

Try below code:

<h2>Click</h2>
<form action="" method="post">
    <button name="click" class="click">Click me!</button>
</form>

    <?php
    if(isset($_POST['click']))
    {
        $filename = "test.txt";
        $before_editing = file_get_contents($filename);

    ?>
<!--this is for display in table-->
<table border="1"><tr><td><?php echo "Content of the file " . $filename . " before editing: " . $before_editing . "<br>"; ?></td></tr></table>
<!-- this is for display in single-->
    <?php
        echo "Content of the file " . $filename . " before editing: " . $before_editing . "<br>";
        file_put_contents($filename, "test test test test test");
        $after_editing = file_get_contents($filename);
        echo "Content of the file " . $filename . " after editing: " . $after_editing . "<br>";
    }
    ?>

You can replace your file name to "test.txt" as i am just giving example to you.

Upvotes: 4

Related Questions