Register Login

How to Call PHP Function from JavaScript?

Updated Jul 26, 2019

As we all know that Javascript is client level scripting language and PHP is Server level programming language. In this tutorial we aim to throw light on how to call PHP function from Javascript with three different example. 

You can call PHP function through Javascript by passing the value, you need as output of PHP function as a string in Javascript.

Example 1:

Call PHP Script from javascript

In this example we define a variable in PHP and we are calling the variable through Javascript.

<?php
// Call PHP Script from javascript

$mydata='Variables declaration in PHP';
?>
<!doctype html>
<html>
<head>
<meta charset="utf-8">
<title>PHP & Javascript</title>
<script type="text/javascript">
	alert("<?php echo $mydata?>");
</script>
</head>

<body>
</body>
</html>

Output: 

Call PHP Function from JavaScript

Example 2:

Call PHP function from javascript without ajax

Here we are decalaring a function "myphpfunction" and printing the return value of declared function in Javascript code.

<?php
// Call PHP function from javascript without ajax

function myphpfunction(){
    $mydata='Call by function declaration PHP';
    return $mydata;
}
?>
<!doctype html>
<html>
<head>
<meta charset="utf-8">
<title>PHP & Javascript</title>
<script type="text/javascript">
    alert("<?php echo myphpfunction()?>");
</script>
</head>
<body>
</body>
</html>

Output:

Call PHP Function from JavaScript

Example 3:

Call PHP function from javascript with parameters

In the following program we are declaring a PHP function “myphpfunction” with the help of two variables x & y. Here we are performing addition operation by storing the value in variable z.

Value of variables x & y is given by Javascript called by PHP function and printing the return value ‘sum of two variables’ in Javascript as output.

<?php
// Call PHP function from javascript with parameters
function myphpfunction($x, $y){
    $z=$x+$y;
    return 'The sum is: '.$z;
}
?>
<!doctype html>
<html>
<head>
<meta charset="utf-8">
<title>Untitled Document</title>
<script type="text/javascript">
    alert("<?php echo myphpfunction(4,90)?>");
</script>
</head>
<body>
</body>
</html>

Output:

Call PHP Function from JavaScript


×