vikky vikky - 7 months ago 19
HTML Question

call js function from php file

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

Answer

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