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....

1
  • 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. Commented Apr 25, 2016 at 11:22

3 Answers 3

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
Sign up to request clarification or add additional context in comments.

Comments

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.

Comments

0

Try This

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

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.