Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Pass PHP variables to Javascript/jquery [duplicate]

So far I know two ways to pass php variables to javascript. One is by using

<script>  
      $(document).ready(function()
          phpvalue=$("#hiddeninput").val()

      })
  </script>

<input type="hidden" id="hiddeninput" value="phpvalue">

And the other one is by having for example a button and using onclick

    <script>
       function clickf(phpvalue) {

       }
    </script>

<input type="submit" onclick="clickf(<?php echo phpvalue ?>)">

All of them work great but:

  1. Is there any other way that I'm missing?

  2. Which one is the "best"?

  3. Any chance that I can use inside the script or the external js ?

like image 945
viper Avatar asked Jan 06 '12 13:01

viper


2 Answers

<script>  
    $(document).ready(function()
        var phpvalue = <?php echo $var; ?>
    });
</script>
like image 113
Alex Pliutau Avatar answered Nov 03 '22 12:11

Alex Pliutau


Like others already answered, just put a PHP tag whereever you would place the JS value, like var foo = <?= $php_value ?>; or var foo = <?php echo $php_value ?>;.

If you want to use this in an external JavaScript file, you have to make sure .js files get parsed by PHP. If this is not an option for you (for example, your host doesn't allow it), I suggest you set the values in a <script> tag inside your <head> and then just reference thos variables from your external JavaScript. In that case, I would strongly suggest you namespace them like var app_vars = { foo: <?= $bar ?> } in order to not clutter the global object.

Another way would be to retreive the values via Ajax. But the viability of this approach depends on your use case.

And another hint: if you want to pass multiple variables or arrays, there's JSON baked into PHP since version 5.2:

<?php
    $my_complex_var = array(
        'array' => array('foo', 'bar'),
        'val2' => 'hello world'
    );
?>
<script>
    var my_complex_js_var = <?= json_encode($my_complex_var) ?>
</script>
like image 26
Rudolph Gottesheim Avatar answered Nov 03 '22 11:11

Rudolph Gottesheim