I am trying to call a PHP function from an external PHP file into a JavaScript script. My code is different and large, so I am writing a sample code here.
This is my PHP code:
<?php
function add($a,$b){
$c=$a+$b;
return $c;
}
function mult($a,$b){
$c=$a*$b;
return $c;
}
function divide($a,$b){
$c=$a/$b;
return $c;
}
?>
This is my JavaScript code:
<script>
var phpadd= add(1,2); //call the php add function
var phpmult= mult(1,2); //call the php mult function
var phpdivide= divide(1,2); //call the php divide function
</script>
So this is what I want to do.
My original PHP file doesn't include these mathematical functions but the idea is same.
If some how it doesn't have a proper solution, then may you please suggest an alternative, but it should call values from external PHP.
index.php
servicios.php
correo.php
This work perfectly for me:
To call a PHP function (with parameters too) you can, like a lot of people said, send a parameter opening the PHP file and from there check the value of the parameter to call the function. But you can also do that lot of people say it's impossible: directly call the proper PHP function, without adding code to the PHP file.
I found a way:
This for JavaScript:
This for a PHP file which isn't your PHP file, but another, which path is written in
url
variable of JS functioncallPHP
, and it's required to evaluate PHP code. This file is called 'phpCompiler.php' and it's in the root directory of your website:So, your PHP code remain equals except return values, which will be echoed:
I suggest you to remember that jQuery is required:
Download it from Google CDN:
or from Microsoft CDN: "I prefer Google! :)"
Better is to download the file from one of two CDNs and put it as local file, so the startup loading of your website's faster!
The choice is to you!
Now you finished! I just tell you how to use
callPHP
function. This is the JavaScript to call PHP:Try looking at CASSIS. The idea is to mix PHP with JS so both can work on client and server side.