Categories
function javascript php

How can I call PHP functions by JavaScript?

65

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.

1

  • 12

    php is server side js is client side. You’ll need to use ajax or page refresh with gets/posts or try creating a js equivalent function.

    – Class

    Apr 2, 2013 at 6:43


93

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

?>

5

  • 9

    Can you explain this code to me? And how to use it under different functions and areguments?

    Jul 23, 2014 at 15:07

  • 1

    Yup, nice answer… I’m just adding to the note about jQuery, that this tends to be slower. Another alternative can be using browser native XMLHttpRequest like for example here blog.garstasio.com/you-dont-need-jquery/ajax/#posting

    – Kuba

    Feb 20, 2019 at 18:20


  • header(‘Content-Type: application/json’); I don’t think you need this line.

    – Nguai al

    Jan 17, 2020 at 9:15

  • i was looking for calling php function when an input change, so this give me a clue i ended up using fetch, Thank you

    – Nald Dev

    Jan 17, 2021 at 4:01


  • @Victor I tried your code but it never goes to my PHP functions

    – Heba

    Dec 1, 2021 at 12:29

44

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>

7

  • 6

    Although this solution works, it is not a clean and a good way to do it. It has tight dependency between client and server code. Much better design would be using ajax to send request to a php page that has the php function call.

    – Shadi

    Feb 1, 2017 at 13:12


  • 1

    <script> var num1; var num2; var phpadd= <?php echo add($num1, $num2);?> </script> Is it possible to call a function this way??

    – A.A Noman

    Feb 26, 2017 at 5:01

  • 2

    @Shadi – I’m curious, what’s wrong with having a “tight dependency between client and server code”? Is there a potential problem, or is this only a matter of “tidy coding”?

    Jan 20, 2020 at 0:25


  • 2

    @ashleedawg good question, as if using Ajax somehow doesn’t require a “tight dependency” between client side and server side..

    May 5, 2020 at 8:24

  • 2

    @statosdotcom your code doesn’t work. You can’t use a JS var in PHP in that way.

    Jun 23 at 20:36

13

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>

1

  • 4

    Make sure when using this that you join up the ‘<?php’ as the script will not work. This code does not format properly in stackoverflow if it is show as ‘< ?php’

    – Mikeys4u

    Feb 24, 2014 at 12:26