Hydlide
Hydlide

Reputation: 363

Create a button that shows information from a text file on the same page

I have my code to display information from a text file already:

$myFile = "file.txt";
$fh = fopen($myFile, 'r');
$theData = fread($fh, filesize($myFile));
fclose($fh);
echo $theData;

But I can't figure out a way to make the above not show until a button is clicked. I tried making it a function but I suppose I wasn't doing it right. I also tried using a submit button that set a cookie and once the cookie was set it displayed the above, but it didn't work either. Are there any other methods to do this? It seems pretty easy, I just can't quite get it to work properly.

Edit: I want to have this all done on one page, no redirecting to another page.

Upvotes: 0

Views: 2336

Answers (2)

aowie1
aowie1

Reputation: 846

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

Although if you are trying to read data dynamically based on what you click, that has to be done via AJAX as mentioned before.

Upvotes: 1

user377628
user377628

Reputation:

Put your code in a PHP file, then (in a separate html file) have a link to that PHP file like this:

<a href="your_file.php">file.txt</php>

edit: Or, as safarov suggested, use AJAX. Either way, your PHP should be in it's own file, since it acts essentially as a remote function.

Upvotes: 0

Related Questions