Pages

2018/09/20

PHP - How to pass variables to Javascript

This post is about how to pass PHP variable to Javascript.

Sample Code (example.php)

<?php
$user = "Bernie";
?>
<div class = "container" style = "background-color:#332B57;">
    <div class = "content">
    </div>
</div>
<div class = "container">
    <div class = "content">
    </div>
</div>
<script>
function welcomeMsg(){
    var user = "<?php echo $user; ?>";
    alert(user);
}
window.addEventListener('load',welcomeMsg);
</script>

The Result


Alternatively, the example.php could be separated into 2 files (example_1.php and example_1.html).

example_1.php

<?php
$user = "Bernie";

include('example_1.html');
?>

example_1.html

<!DOCTYPE HTML>
<html>
<head>
<script>
function welcomeMsg(){
    var user = "<?php echo $user; ?>";
    alert(user);
}
window.addEventListener('load', welcomeMsg);
</script>
</head>
<body>
<div class = "container" style = "background-color:#332B57;">
    <div class = "content">
    </div>
</div>
<div class = "container">
    <div class = "content">
    </div>
</div>
</body>
</html>            

The Result


Reference:

How to pass PHP variables to javascript
https://www.youtube.com/watch?v=2QFfkC2CCZM

No comments:

Post a Comment