Home > other >  php button does not call function
php button does not call function

Time:05-28

I have some php code that is meant to write variables in an array to a file when clicking a button, but the code I have for the button onclick event doesnt seem to be called at all, the echo line doesnt even display at all. Everything works fine except for the button, doesnt even give any warning/error messages so I am kind of lost on what the problem is. Here is the code for reference:

<?php
session_start();
$arr = $_SESSION['arr'];
session_destroy();
?>

<!DOCTYPE html>
<html lang = "en">
    <body>
        <h1> Selected tasks <br></h1>

        <?php 
            foreach($arr as $selected)
                echo $selected ."<br>" ."<br>";
        ?>

        <button onclick = "clicked()"> Export </button>

        <?php 
            function clicked() {
                echo "function called";
                $myfile = fopen("To Do List.txt", "w") or die("Unable to open file!");

                foreach($arr as $selected)
                    fwrite($myFile, $selected . "\n");

                fclose($myfile);
            }
        ?>
    </body>
</html>
    

CodePudding user response:

PHP code runs on server-side to output HTML code for client's browser. After the HTML code (that generated by PHP on the server) is downloaded to the client's browser, when that button is clicked, the browser calls a JavaScript function clicked(), not a PHP function.

CodePudding user response:

<?php
session_start();
$arr = $_SESSION['arr'];
session update();   
session_destroy();
?>

<!DOCTYPE html>
<html lang = "en">
    <body>
        <h1> Selected tasks <br></h1>

        <?php 
            foreach($arr as $selected)
                echo $selected ."<br>" ."<br>";
        ?>

        <button onclick = "clicked()"> Export </button>

        <?php 
            function clicked() {
                echo "function called";
                $myfile = fopen("To Do List.txt", "w") or die("Unable to open file!");

                foreach($arr as $selected)
                    fwrite($myFile, $selected . "\n");

                fclose($myfile);
            }
        ?>
    </body>
</html>
  •  Tags:  
  • php
  • Related