How can I call PHP functions by JavaScript?
How can I call PHP functions by JavaScript?
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>
How can I call PHP functions by JavaScript?
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>