简体   繁体   中英

Passing PHP integer variable value to JavaScript

I need to pass variable from php to javascript. Yes, I have read couple of questions on StackOverflow and tried many possibilities. Still no success.

I recently used following code for passing value:

<?php $num= 1970; ?>
...
<script type="text/javascript">
var num = "<?php echo $num; ?>";
</script>

(I used it without echo too - no way). I'm trying value saved in variable $num pass to

            [Date.UTC(1970, 10, 26), 0.25],
            [Date.UTC(num , 11, 6), 0],
            [Date.UTC(1970, 11, 20), 1.41],
            [Date.UTC(1970, 11, 25), 1.64],
            [Date.UTC(1971, 0, 4), 1.6],

This solution doesn't work, obviously.

Change

var num = "<?php echo $num; ?>";

to

var num = <?php echo $num; ?>;

Of course, you should know that PHP executes before the page is sent to a Browser, so if you're looking for this to happen dynamically look into AJAX.

You can physically write the PHP code to the DOM, and then use JavaScript to target the DOM element:

<?php
$num = 1970;
echo "<div id='num'>" . $num . "</div>"; // <div id='num'>1970</div>
?>

<script type="text/javascript">
var num = parseInt(document.getElementById('num').innerHTML);
console.log(num); // 1970
</script>

<style>
#num {
  display: none; /* Hide the element */
}
</style>

This way you can access the PHP variable without the JavaScript needing to be coded into the PHP file itself.

I've also created a working example of this through PHPFiddle .

Hope this helps! :)

you can echo javascript in php

<?php $num= 1970; 

    echo"<script>alert('$num');</script>";
?>

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM