Home > Software engineering >  php call a js function that is defined on different js file
php call a js function that is defined on different js file

Time:03-03

I am trying to call

this js function that is stored on a file called default.js from a php file.

function myfunction(score) {
  console.log("got here");
  alert(score);
}

so this is the call for the js function on my php code but it does not work.

<!-- myfunction js file ↓ -->
        <script type="text/javascript" src="../js/default.js"></script>
        <?php

            
            if ($grade=="100%"){
                // not able to call
            echo "myfunction($grade)";
   
            }
            else{

                echo "alert(\"haha\")";
            }
            
        ?>

CodePudding user response:

Try this you will get the accurate result

<?php
    if ($grade == "100%") {
    ?>
        <script>
            myfunction('<?=$grade?>');
        </script>
    <?php
    } else {
    ?>
    <script>
    alert('in');
    </script>
    <?php } ?>

CodePudding user response:

This is your Code.

Define $grade too in PHP or you get a <b>Warning</b>: Undefined variable $grade in <b>

<script type="text/javascript" src="../js/default.js"></script>
<script>
<?php
    $grade = "10%";
    if ($grade=="100%"){
        echo "myfunction('$grade')";
   }
    else{
       echo 'alert("haha");';
 }
            
?>
</script>

Dont forget the <script></script> for javascript code inside html.

CodePudding user response:

you forgot about the <script> tags change your echo like this:

echo "<script>myfunction('$grade')</script>"; 

you need to wrap ' around the $grade because you're passing a string


or put <script> before the opening php tag and </script> after the end of php tag

  • Related