Dani
Dani

Reputation: 41

How to call js function from php?

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>

Upvotes: 3

Views: 16969

Answers (4)

Dani
Dani

Reputation: 41

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

Upvotes: 1

Peter
Peter

Reputation: 9123

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.

Upvotes: 1

Nuno Valente
Nuno Valente

Reputation: 143

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

Upvotes: 0

Shubham
Shubham

Reputation: 1793

You can call javascript function like this :

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

But function should be defined already.

Upvotes: 4

Related Questions