Run a JavaScript function from a php if statement

后端 未结 5 2217
余生分开走
余生分开走 2020-12-04 01:39

I am using PHP conditions and want to know if I can run a JavaScript function without some one have to click on it using JavaScript:

if($value == 1)             


        
相关标签:
5条回答
  • 2020-12-04 02:13

    I know this thread is old but I just came across it and wanted to add my technique.

    You can also echo the php variable into JavaScript and do something based on its value. I use it to place database values into js so the user can do math on the page with them

        <script>
    var jsvar = <?php echo $phpvar ;?>
    if (jsvar = x){ do something...}
    </script>
    
    0 讨论(0)
  • 2020-12-04 02:17

    I've found that you cannot do something like this in IE and other browsers. It does work in Firefox though. You have to echo out each line as posted in the other method.

    <?php
    if(somecondition)
      {
    ?>
    
    <script>
    Some javascript code
    </script>
    
    <?php
      }
    ?>
    
    0 讨论(0)
  • 2020-12-04 02:21

    First of all keep in mind that your PHP code is evaluated on the server, while JavaScript runs in the browser on the client-side. These evaluations happen in different places, at different times. Therefore you cannot call a JavaScript function from PHP.

    However with PHP you can render HTML and JavaScript code such that it is only rendered when your PHP condition is true. Maybe you may want to try something like this:

    if($value == 1) {
       echo "<script>";
       echo "alert('This is an alert from JavaScript!');";
       echo "</script>";
    } 
    
    0 讨论(0)
  • 2020-12-04 02:24

    Javascript is client-side code, PHP is server-side, so you cannot execute javascript while building the page in PHP.

    To execute javascript on the client-side as soon as the page has loaded, one way is to use the body onload handler to call your function:

    <?php
    echo '<script type="text/javascript">';
    echo 'function myFunction(){ /* do_something_in_javascript */ };';
    echo '</script>';
    
    if ($value == 1) {
        echo '<BODY onLoad="myFunction()">';
    }
    ?>
    

    Better yet, if you can afford the bandwidth, use jQuery and use $(document).ready():

    <?php
    if ($value == 1) {
        echo '<script type="text/javascript">';
        echo '$(document).ready(function(){ /* do_something_in_javascript */ });';
        echo '</script>';
    }
    ?>
    
    0 讨论(0)
  • 2020-12-04 02:26

    After some tinkering, I was able to get the following to work within a .php file. This doesn't work in a .html file though.

    <?php
    if (isset($_SESSION['loggedin'])) {$login='t';}else{$login='f';}
    ?>
    
    <script>
    var login = "<?php echo $login ?>";
    console.log(login);
    
    if (login == 'f'){ .. do something..}
    
    0 讨论(0)
提交回复
热议问题