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>
0

4 Answers 4

4

You can call javascript function like this :

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

But function should be defined already.

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

Comments

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.

Comments

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

Comments

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

3 Comments

Still the same problem
echo '<button type="button" id='.$i.' class="button" OnClick=mappanyitas("'.trim($mappak[$i]).'")>'.trim($filename).'</button>';
Yes you're right! Good thinking :) Hope your problem has been solved!

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.