using php in javascript 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: how to run php inside js

You can't run PHP with javascript. JavaScript is a client 
side technology (runs in the users browser) and PHP is a 
server side technology (run on the server). If you want to 
do this you have to make an ajax request to a PHP script and 
have that return the results you are looking for.

Tags:

Php Example