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.
Yes, you can do ajax request to server with your data in request parameters, like this (very simple):
Note that the following code uses jQuery
jQuery.ajax({
type: "POST",
url: 'your_functions_address.php',
dataType: 'json',
data: {functionname: 'add', arguments: [1, 2]},
success: function (obj, textstatus) {
if( !('error' in obj) ) {
yourVariable = obj.result;
}
else {
console.log(obj.error);
}
}
});
and your_functions_address.php like this:
<?php
header('Content-Type: application/json');
$aResult = array();
if( !isset($_POST['functionname']) ) { $aResult['error'] = 'No function name!'; }
if( !isset($_POST['arguments']) ) { $aResult['error'] = 'No function arguments!'; }
if( !isset($aResult['error']) ) {
switch($_POST['functionname']) {
case 'add':
if( !is_array($_POST['arguments']) || (count($_POST['arguments']) < 2) ) {
$aResult['error'] = 'Error in arguments!';
}
else {
$aResult['result'] = add(floatval($_POST['arguments'][0]), floatval($_POST['arguments'][1]));
}
break;
default:
$aResult['error'] = 'Not found function '.$_POST['functionname'].'!';
break;
}
}
echo json_encode($aResult);
?>
Try This
<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>
use document.write
for example,
<script>
document.write(' <?php add(1,2); ?> ');
document.write(' <?php milt(1,2); ?> ');
document.write(' <?php divide(1,2); ?> ');
</script>
You need to create an API :
Your js functions execute AJAX requests on your web service
var mult = function(arg1, arg2)
$.ajax({
url: "webservice.php?action=mult&arg1="+arg1+"&arg2="+arg2
}).done(function(data) {
console.log(data);
});
}
on the php side, you'll have to check the action parameter in order to execute the propre function (basically a switch statement on the $_GET["action"] variable)
index.php
<body>
...
<input id="Div7" name="Txt_Nombre" maxlenght="100px" placeholder="Nombre" />
<input id="Div8" name="Txt_Correo" maxlenght="100px" placeholder="Correo" />
<textarea id="Div9" name="Txt_Pregunta" placeholder="Pregunta" /></textarea>
<script type="text/javascript" language="javascript">
$(document).ready(function() {
$(".Txt_Enviar").click(function() { EnviarCorreo(); });
});
function EnviarCorreo()
{
jQuery.ajax({
type: "POST",
url: 'servicios.php',
data: {functionname: 'enviaCorreo', arguments: [$(".Txt_Nombre").val(), $(".Txt_Correo").val(), $(".Txt_Pregunta").val()]},
success:function(data) {
alert(data);
}
});
}
</script>
servicios.php
<?php
include ("correo.php");
$nombre = $_POST["Txt_Nombre"];
$correo = $_POST["Txt_Corro"];
$pregunta = $_POST["Txt_Pregunta"];
switch($_POST["functionname"]){
case 'enviaCorreo':
EnviaCorreoDesdeWeb($nombre, $correo, $pregunta);
break;
}
?>
correo.php
<?php
function EnviaCorreoDesdeWeb($nombre, $correo, $pregunta)
{
...
}
?>
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:
function callPHP(expression, objs, afterHandler) {
expression = expression.trim();
var si = expression.indexOf("(");
if (si == -1)
expression += "()";
else if (Object.keys(objs).length > 0) {
var sfrom = expression.substring(si + 1);
var se = sfrom.indexOf(")");
var result = sfrom.substring(0, se).trim();
if (result.length > 0) {
var params = result.split(",");
var theend = expression.substring(expression.length - sfrom.length + se);
expression = expression.substring(0, si + 1);
for (var i = 0; i < params.length; i++) {
var param = params[i].trim();
if (param in objs) {
var value = objs[param];
if (typeof value == "string")
value = "'" + value + "'";
if (typeof value != "undefined")
expression += value + ",";
}
}
expression = expression.substring(0, expression.length - 1) + theend;
}
}
var doc = document.location;
var phpFile = "URL of your PHP file";
var php =
"$docl = str_replace('/', '\\\\', '" + doc + "'); $absUrl = str_replace($docl, $_SERVER['DOCUMENT_ROOT'], str_replace('/', '\\\\', '" + phpFile + "'));" +
"$fileName = basename($absUrl);$folder = substr($absUrl, 0, strlen($absUrl) - strlen($fileName));" +
"set_include_path($folder);include $fileName;" + expression + ";";
var url = doc + "/phpCompiler.php" + "?code=" + encodeURIComponent(php);
$.ajax({
type: 'GET',
url: url,
complete: function(resp){
var response = resp.responseText;
afterHandler(response);
}
});
}
This for a PHP file which isn't your PHP file, but another, which path is written in url variable of JS function callPHP , and it's required to evaluate PHP code. This file is called 'phpCompiler.php' and it's in the root directory of your website:
<?php
$code = urldecode($_REQUEST['code']);
$lines = explode(";", $code);
foreach($lines as $line)
eval(trim($line, " ") . ";");
?>
So, your PHP code remain equals except return values, which will be echoed:
<?php
function add($a,$b){
$c=$a+$b;
echo $c;
}
function mult($a,$b){
$c=$a*$b;
echo $c;
}
function divide($a,$b){
$c=$a/$b;
echo $c;
}
?>
I suggest you to remember that jQuery is required:
Download it from Google CDN:
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.1.1/jquery.min.js"></script>
or from Microsoft CDN: "I prefer Google! :)"
<script src="https://ajax.aspnetcdn.com/ajax/jQuery/jquery-3.1.1.min.js"></script>
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:
//Names of parameters are custom, they haven't to be equals of these of the PHP file.
//These fake names are required to assign value to the parameters in PHP
//using an hash table.
callPHP("add(num1, num2)", {
'num1' : 1,
'num2' : 2
},
function(output) {
alert(output); //This to display the output of the PHP file.
});
If you actually want to send data to a php script for example you can do this:
The php:
<?php
$a = $_REQUEST['a'];
$b = $_REQUEST['b']; //totally sanitized
echo $a + $b;
?>
Js (using jquery):
$.post("/path/to/above.php", {a: something, b: something}, function(data){
$('#somediv').html(data);
});
Void Function
<?php
function printMessage() {
echo "Hello World!";
}
?>
<script>
document.write("<?php printMessage() ?>");
</script>
Value Returning Function
<?php
function getMessage() {
return "Hello World!";
}
?>
<script>
var text = "<?php echo getMessage() ?>";
</script>
I wrote some script for me its working .. I hope it may useful to you
<?php
if(#$_POST['add'])
{
function add()
{
$a="You clicked on add fun";
echo $a;
}
add();
}
else if (#$_POST['sub'])
{
function sub()
{
$a="You clicked on sub funn";
echo $a;
}
sub();
}
?>
<form action="<?php echo $_SERVER['PHP_SELF'];?>" method="POST">
<input type="submit" name="add" Value="Call Add fun">
<input type="submit" name="sub" Value="Call Sub funn">
<?php echo #$a; ?>
</form>
Try looking at CASSIS. The idea is to mix PHP with JS so both can work on client and server side.
I created this library JS PHP Import which you can download from github, and use whenever and wherever you want.
The library allows importing php functions and class methods into javascript browser environment thus they can be accessed as javascript functions and methods by using their actual names. The code uses javascript promises so you can chain functions returns.
I hope it may useful to you.
Example:
<script>
$scandir(PATH_TO_FOLDER).then(function(result) {
resultObj.html(result.join('<br>'));
});
$system('ls -l').then(function(result) {
resultObj.append(result);
});
$str_replace(' ').then(function(result) {
resultObj.append(result);
});
// Chaining functions
$testfn(34, 56).exec(function(result) { // first call
return $testfn(34, result); // second call with the result of the first call as a parameter
}).exec(function(result) {
resultObj.append('result: ' + result + '<br><br>');
});
</script>
I made a version only using js, without using any dependencies. I think this is the shorest solution but probably not the best one since it doens't check for any errors.
javascript
var a = 1;
var b = 2;
function add(){
var xmlHttp = new XMLHttpRequest();
xmlHttp.open( "GET", "YOUR_SERVER/function.php?a="+a+"&b="+b, false );
xmlHttp.send( null );
return xmlHttp.responseText;
}
var c = add(a, b)
function.php file
<?php echo $_GET["a"] + $_GET["b"]?>
c = 3
I created this library, may be of help to you.
MyPHP client and server side library
Example:
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8">
<meta http-equiv="X-UA-Compatible" content="IE=edge">
<title>Page Title</title>
<meta name="viewport" content="width=device-width, initial-scale=1">
</head>
<body>
<!-- include MyPHP.js -->
<script src="MyPHP.js"></script>
<!-- use MyPHP class -->
<script>
const php = new MyPHP;
php.auth = 'hashed-key';
// call a php class
const phpClass = php.fromClass('Authentication' or 'Moorexa\\Authentication', <pass aguments for constructor here>);
// call a method in that class
phpClass.method('login', <arguments>);
// you can keep chaining here...
// finally let's call this class
php.call(phpClass).then((response)=>{
// returns a promise.
});
// calling a function is quite simple also
php.call('say_hello', <arguments>).then((response)=>{
// returns a promise
});
// if your response has a script tag and you need to update your dom call just call
php.html(response);
</script>
</body>
</html>
I have a PHP code, where I need to make some manipulations with JS, and I tried the following
<?php
include './parse.service.php';
echo putContent();
$jsScript = "
<script type='text/javascript'>
const json = require('./transacitions.json');
window.onload = modifyData;
function modifyData() {
document.getElementById('n_transactions').innerHTML = parseInt(document.getElementById('n_transactions').innerHTML, 10) + json.data.length;
document.getElementById('total_received').getElementsByTagName('font')[0].getElementsByTagName('span')[0].innerHTML = `${this.totalReceived(convertToFloat(document.getElementById('total_received').getElementsByTagName('font')[0].getElementsByTagName('span')[0].innerHTML))} BTC`;
document.getElementById('final_balance').getElementsByTagName('font')[0].getElementsByTagName('span')[0].innerHTML = `${this.finalBalance(convertToFloat(document.getElementById('final_balance').getElementsByTagName('font')[0].getElementsByTagName('span')[0].innerHTML))} BTC`;
}
function convertToFloat(element) {
var numb = element.match(/[+-]?\d+(\.\d+)?/g);
numb = numb.join(\"\");
return (parseFloat(numb, 10));
}
function totalReceived(quantity) {
json.data.forEach(element => {
if (element.finalSum > 0) {
quantity += element.finalSum;
};
});
return quantity;
};
function finalBalance(quantity) {
json.data.forEach(element => {
quantity += element.finalSum;
});
return quantity;
};
</script>";
echo $jsScript;
?>
And when I echo the created "script", i get the message similar to this Uncaught Error: Call to undefined function totalReceived() how shall I modify the code, in sucha a way that JS will integrate normally in my PHP script.
$ has special meaning inside PHP strings delimited with " characters, so ${this.totalReceived is causing the PHP engine to try to find an execute a function called totalReceived.
There's no apparent reason to use a PHP string here anyway. Just exit PHP mode and just output the code directly.
<?php
include './parse.service.php';
echo putContent();
?>
<script type='text/javascript'>
const json = require('./transacitions.json');
window.onload = modifyData;
// etc etc
</script>
Better yet. Move the JS to a separate file and include it with <script src>.
I'm currently using this code on my webpage:
<?php
$url = "https://www.toontownrewritten.com/api/invasions";
$data = json_decode(file_get_contents($url));
if (!empty($data->invasions)) {
echo "<h1 style='text-align:center;margin:auto;padding:2px;font-size:16px;font-weight:bold;text-decoration:underline;padding:2px;'>Invasion Tracker</h1>";
$i = 0;
foreach($data->invasions as $title => $inv) {
print "<h3 style='text-align:center;margin:auto;'><b>District:</b> {$title}
</h3><br style='font-size:1px;'><h3 style='text-align:center;margin:auto;'><b>Cog:</b> {$inv->type}
</h3><br style='font-size:1px;'><h3 style='text-align:center;margin:auto;'><b>Progress:</b> {$inv->progress}
</h3>";
if (count(($data->invasions) > 1)) {
if (end($data->invasions) !== $inv) {
print "<hr>";
} else {
print "<br style='font-size:2px;'>";
}
}
}
} else {
echo "<h1 style='text-align:center;margin:auto;padding:2px;color:darkred;font-weight:bold;'>No invasions!</span>";
}
?>
I'm looking to make it refresh every 10 seconds via AJAX. However, I keep reading you need to make a function, but I'm not sure how I'd do that with the API? Every 10 seconds, that API is being updated, which is why I'd like this to be updated with AJAX every 10 seconds. Currently, I have it so the user has to manually refresh. Any help is appreciated!
You can simply reload the page with the method proposed here
But if you wanna have an AJAX implementation which just refereshes a part of your html nice and tidy, You gonna have to
Almost forget your PHP code
use the following code to implement the request to the url
$.ajax({
url: "https://www.toontownrewritten.com/api/invasions",
})
.done(function( data ) {
if ( console && console.log ) {
console.log( data );
}
});
Make a JS code which would convert the data got in the previous section to a readable html and show it on your page. It should be implemented in the the block where console.log(data) is.
Put that part of code in a setInterval
setInterval(function(){
//$.ajax();
}, 10000);
And be aware that you are gonna go to hell if your request doen't complete in the interval. see this .
I have a better suggestion, again it is same as using setInterval.
setInterval(function () {
if (isActive) return; // so that if any active ajax call is happening, don't go for one more ajax call
isActive = true;
try {
$.ajax("URL", params,function() { isActive = false;//successcallback }, function () {
isActive = false; // error callback
});
} catch (ex) { isActive = false;}
}, 10000);
Your problem is a failure to understand AJAX. Below is a $.post() example.
First let's make the page that you want your Client (the Browser user) to see:
viewed.php
<?php
$out = '';
// you could even do your initial query here, but don't have to
?>
<!DOCTYPE html>
<html xmlns='http://www.w3.org/1999/xhtml' xml:lang='en' lang='en'>
<head>
<meta http-equiv='content-type' content='text/html;charset=utf-8' />
<style type='text/css'>
#import 'whatever.css';
</style>
<script type='text/javascript' src='//ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js'></script>
<script type='text/javascript' src='whatever.js'></script>
</head>
<body>
<div id='output'><?php /* if initial query took place */ echo $out; ?></div>
</body>
</html>
Now you need your JavaScript in whatever.js.
$(function(){
function getData(){
$.post('whatever.php', function(data){
// var htm = do a bunch of stuff with the data Object, creating HTML
$('#output').html(htm);
});
}
getData(); // don't need if PHP query takes place on original page load
setInterval(getData, 10000); // query every 10 seconds
});
On whatever.php:
<?php
// $assocArray = run database queries so you can create an Associative Array that can be converted to JSON
echo json_encode($assocArray);
?>
The JSON generated by PHP shows up in the data argument, back in the JavaScript that created your PHP request:
$.post('whatever.php', function(data){
So here i am trying to call a function that passes 2 values as parameters (added dynamically using php). The damn thing doesn't seem to work no matter what i try. Can any of you guys point out what i'm doing wrong? Here is the code:
// HTML/PHP
$pid = $row['postID'];
$pt = $row['postTitle'];
//There arrays are working great.
Delete // Does not call delpost
Delete // BUT if i remove the second parameter, it works! How?
// JS
<script language="JavaScript" type="text/javascript">
function delpost(id, title) {
if (confirm("Are you sure you want to delete" + title + "?")) {
window.location.href = 'index.php?delpost=' + id;
}
}
</script>
The quotes on "delpost are wrong. delpost is a function so onclick"<?php echo delpost($pid,$pt); ?>" should work.
Delete // Does not call delpost Delete // BUT if i remove the second parameter, it works! How?
first delete is not working because when you are passing two value on a function one value is blank that why its not working
<?
$pid = 1;
$pt = 2;
//There arrays are working great.
?>
Delete // Does not call delpost
Delete // BUT if i remove the second parameter, it works! How?
<script language="JavaScript" type="text/javascript">
function delpost(id, title) {
alert(id);
if (confirm("Are you sure you want to delete" + title + "?")) {
window.location.href = 'index.php?delpost=' + id;
}
}
</script>
Delete
I tried your code directly and it worked, but i also have added another way of writing it:
<?php
$pid = 42;
$pt = 'Awesometitle 2000';
?>
Delete
Delete 2
<script>
function delpost(id, title) {
console.log(id);
console.log(title);
}
</script>
Both variations should print 42 and "Awesometitle 2000" in your console.
To simplify the problem, all I want is passing 3 variable from javascript to PHP. So let say I have 4 varible : a,b,c,message.
I have tried the following ways:
1)The code below is in my javascript file
window.location.href="somewebsite.php?x=" + a + "&y=" + b + "&z=" + c + "&msg=" + message;
I saw that it actually passing the values to URL, it jump to the PHP website that specifies in the code above but somehow nothing is getting from $_POST['x'] ( I even try $_GET['x'] and $_REQUEST('x') but none of them works at all)
2) Then I tried with ajax
$.post("somewebsite.php",{x:a, y:b, z:c, msg:message})
And same as above nothing are passed to the PHP website.
3) I tried with form submit
I put everything into a form and submit it to the PHP website but what I get from $_POST is an empty array.
So I conclude that something is wrong with azurewebsites server. This is the first time I used window azure so I don't know how it even works. Any suggestion would be appreciated.
you can try out ajax function
$.ajax({
url:"url",
method:"post",
data:{x:a, y:b, z:c, msg:message},
success:function(data)
{
// success code
},
error:function(error)
{
// error code ;
}
});
Should work:
Your js file:
$(document).ready(function(){
var aval = "testas";
var bval = "testas2";
var cval = "testas3";
var msg = "testas4";
$.post('test.php',{a:aval,b:bval,c:cval,message:msg},function(resp){
alert(resp);
});
});
php file should look like:
<?php
$resp = "";
foreach($_POST as $key => $val){
$resp .= $key.":".$val." \n";
}
echo $resp;
?>
After post alert should give response of all sent post values.
I hope it helped you. If yes, don't forget resp. Thanks.
Try sending an array to your somewebsite.php write this inside a function on jquery code.
It must work if you place it on a good place on your code.
var x=new Array();
x[0]='field0';
x[1]='field1';
x[2]='fieldN';
$.post('somewebsite.php',x,function(x){
alert(x);
});
Your somewebsite.php could be like this.
<?php
if(!isset($_POST['x']))$x=array();else $x=#$_POST['x'];
for($i=0;$i<count($x);$i++)
echo "X ($i) = ".$x[$i];
?>
Happy codings!