1

I have a js file.

jiten.js

function myFunction(p1, p2) {
    return p1 * p2;   
    };

I have to call this function from php file

Demo.php

<?xml version="1.0" encoding="UTF-8" standalone="no"?>
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">
  <head>
    <title>Mosquitto Websockets</title>
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <script src="jiten.js" type="text/javascript"></script>
  </head>
  <body>
 <?php 
    echo '<script type="text/javascript">myFunction(2,4);</script>'; 
?>    
  </body>
</html>

But When I run this file, I get nothing....

jiten
  • 5,128
  • 4
  • 44
  • 73
  • What do you expect it to do? What you have above will call the function, which will do as expected, but then simply return a result. It doesn't _do_ anything with the result. Put it in an alert and you should see that it's working. – Reinstate Monica Cellio Apr 25 '16 at 11:22

3 Answers3

2

Your code is working well, but your Javascript function doesn't display anything, it just returns a value.

You should use something like console.log() or alert() to display the result.

Aurel
  • 631
  • 3
  • 18
2

PHP and JavaScript are different languages, they can be embedded but, each language has to call its own functions.

You are returning value through JavaScript code, but, you can not echo it with PHP and not printing it through JavaScript.

You need to print the value by using document.write() in JavaScript.

Corrected Code:

<script type="text/javascript">
function myFunction(p1, p2) {
  return p1 * p2;   
  };
</script>
<?php
echo '<script type="text/javascript">document.write(myFunction(2,4));</script>';
?>

Output:

8
Pupil
  • 23,834
  • 6
  • 44
  • 66
0

Try This

echo '<script type="text/javascript">document.write(myFunction(2,4));   
KAREN
  • 388
  • 2
  • 10