php in javascript function code example

Example 1: function php

function functionName() {
    //code to be executed;
}

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: call php function in js

<script>
  var phpadd= <?php echo add(1,2);?> //call the php add function
  var phpmult= <?php echo mult(1,2);?> //call the php mult function
  var phpdivide= <?php echo divide(1,2);?> //call the php divide function
</script>

Example 4: 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