How to call PHP function through JavaScript?
P粉133321839
P粉133321839 2023-07-30 18:57:00
0
2
597
<p>I'm trying to call a PHP function from an external PHP file into a JavaScript script. My code is more complex, so I'm writing a sample code here. </p><p>This is my PHP code: </p> <pre class="lang-php prettyprint-override"><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; } ?> </code></pre> <p>JS code:</p> <pre class="brush:php;toolbar:false;"><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></pre> <p>This is what I want to do. </p><p>My original PHP file did not contain these math functions, but the idea is the same. </p><p>If there is no suitable solution, can you please provide an alternative, but it should call the value from an external PHP file. </p><p><strong></strong></p>
P粉133321839
P粉133321839

reply all(2)
P粉396248578

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>
P粉235202573

Yes, you can send an Ajax request with data to the server using request parameters, like this (very simple):

Please 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);
                  }
            }
});

Your _functions_address.php file should look 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);

?>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template