How can I call PHP functions by JavaScript?

后端 未结 11 1186
情话喂你
情话喂你 2020-11-22 12:08

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 m

相关标签:
11条回答
  • 2020-11-22 12:37

    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);
    
    ?>
    
    0 讨论(0)
  • 2020-11-22 12:37

    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>
    
    0 讨论(0)
  • 2020-11-22 12:39

    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>
    
    0 讨论(0)
  • 2020-11-22 12:39

    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.
            });
    
    0 讨论(0)
  • 2020-11-22 12:39

    Try looking at CASSIS. The idea is to mix PHP with JS so both can work on client and server side.

    0 讨论(0)
  • 2020-11-22 12:46

    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)
        { 
           ...
        }
    ?>
    
    0 讨论(0)
提交回复
热议问题