javascript code in php code example
Example 1: javascript inside php
<?php
FONCTION_PHP(){
?>
<script>
function fonctionJavaScript(){
}
</script>
<?php
}
?>
Example 2: php in javascript
If your whole JavaScript code gets processed by PHP, then you can do it just like that.
If you have individual .js files, and you don't want PHP to process them (for example, for caching reasons), then you can just pass variables around in JavaScript.
For example, in your index.php (or wherever you specify your layout), you'd do something like this:
<script type="text/javascript">
var my_var = <?php echo json_encode($my_var); ?>;
</script>
You could then use my_var in your JavaScript files.
This method also lets you pass other than just simple integer values, as json_encode() also deals with arrays, strings, etc. correctly, serialising them into a format that JavaScript can use.
Example 3: php into javascript
$str = <<<MY_MARKER
<script type="text/javascript">
document.write("Hello World!");
</script>
MY_MARKER;
echo $str;