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 ?

Answers:

Answer
<script>  
    $(document).ready(function()
        var phpvalue = <?php echo $var; ?>
    });
</script>
Answer

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>
Answer
<script>

var javascript_variable = <?php echo $php_variable; ?>;

</script>
Answer

Instead of assigning values to hidden inputs, you could just generate JavaScript directly:

$script = <<<EOT
<script>
var phpvalue = $phpvalue;
</script>
EOT;
echo $script;
Answer

for the top example you do not need to use val you could use any attr you like. For example

phpvalue="myvalue"

then within jquery

$("#hiddeninput").attr("phpvalue");

Tags

Recent Questions

Top Questions

Home Tags Terms of Service Privacy Policy DMCA Contact Us

©2020 All rights reserved.