3

I have a php page, a html button on it and there I should call a JS function with a php variable. And I get the error

the variable is not defined

Here is the code:

<body>
    <form  class="form">
    <?php
    if(file_exists('megjelenitendo.txt')){
        $mappak=array();
        $mappakdb=0;
        $megjelenitendo = fopen("megjelenitendo.txt", "r") or die("Unable to open file!");
        while(!feof($megjelenitendo)) {
             $mappak[$mappakdb]=fgets($megjelenitendo) ;
             $mappakdb++;
            }   
        fclose($megjelenitendo);
        $j=0;

        foreach(glob('*') as $filename){
            for($i=0; $i<$mappakdb;++$i){
            //echo $filename."==".$mappak[$i];echo "<br>";
            if(strtoupper($filename)==strtoupper(trim($mappak[$i]))){
             //echo '<button type="submit" id='.$i.' class="button" formaction='.$filename.' />'.$filename;//substr($filename, 3,strlen($filename));
            echo '<button type="button" id='.$i.' class="button" OnClick=mappanyitas('.trim($mappak[$i]).')>'.trim($filename).'</button>';
             echo '<br>';         
         }
             else{} 
         }
     }}

     else{
        echo "A mappa elemei:<br>";
     }
    ?>
    </form>

    <script type="text/javascript">
         function mappanyitas(filename){
            alert(filename);
        }

    </script>
</body>
Mr.7
  • 2,292
  • 1
  • 20
  • 33
Dani
  • 41
  • 1
  • 1
  • 3
  • Possible duplicate of [How to call a JavaScript function from PHP?](http://stackoverflow.com/questions/1045845/how-to-call-a-javascript-function-from-php) – mdameer Nov 25 '16 at 11:18

4 Answers4

4

You can call javascript function like this :

<?php 
    echo "<script>functionName();</script>";
?>

But function should be defined already.

Shubham
  • 1,755
  • 3
  • 17
  • 33
1

The way to get PHP variables to javascript that I tend to use is just set the variable :)

<script type="text/javascript">
var fromPHP = '<?= $phpVariable; ?>';
</script>

Ti's as simple as that.

Peter
  • 8,776
  • 6
  • 62
  • 95
1
echo '<button type="button" id='.$i.' class="button" OnClick=mappanyitas("'.trim($mappak[$i]).'")>'.trim($filename).'</button>';
Dani
  • 41
  • 1
  • 1
  • 3
0

try this line

echo '<button type="button" id='.$i.' class="button" onclick="mappanyitas('.trim($mappak[$i]).')">'.trim($filename).'</button>'

Let me know if this solved your problem!

P.S. Check the rendered page's HTML and check the button's code, to check if the variable's value was successfully injected into the code

Nuno Valente
  • 143
  • 2
  • 12