Can javascript call a php function?

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:



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:

//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.
        });

There are two ways of calling a PHP function from JavaScript depending on your web project’s architecture:

  • You can call PHP function inline from the

When you open your index.php file from the browser, you will see the HTML rendered as follows:

<body>
  <h2 id="header">8h2>
  <script>
    const result = 8;
    document.getElementById("header").innerHTML = result;
  script>
body>

Any PHP code that you include inside your HTML page will be processed on the server-side before being served to the browser.

When you call a PHP function inline from JavaScript as shown above, you can’t use dynamic values from user input.

If you want to call PHP function as a response to user action, then you need to send HTTP request from JavaScript to the PHP file. Let’s learn that next.

Call PHP function from JavaScript over HTTP request

To send HTTP request from JavaScript to PHP server, you need to do the following:

  • separate your PHP file from your HTML file
  • Call the PHP function over an HTTP request using fetch() JavaScript method

First, separate your PHP function in a different file. Let’s call the file add.php and put the following content inside it:

php
$x = $_POST['x'];
$y = $_POST['y'];

echo $x + $y;
?>

Next, create an index.html file in the same folder where you created the add.php file and put the following content inside it:

<body>
  <button id="add">Add 5 + 3button>
  <div id="result">div>
  <script>
    let btn = document.getElementById("add");
    let x = 5;
    let y = 3;

    btn.addEventListener("click", function(){
      fetch("http://localhost:8000/add.php", {
        method: "POST",
        headers: {
          "Content-Type": "application/x-www-form-urlencoded; charset=UTF-8",
        },
        body: `x=${x}&y=${y}`,
      })
      .then((response) => response.text())
      .then((res) => (document.getElementById("result").innerHTML = res));
    })
  script>
body>

The fetch() method will be executed each time the