Call PHP Function from JavaScript

How can I call PHP functions by JavaScript?

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

?>

Calling PHP function Onchange on Javascript

You can try to use ajax to call the php script and receive results back to javascript.

For example in your html page:

<div class="col-sm-4 form-group">
<label for="c_city">City</label>
<select class="form-control" id="c_city" onchange="getArea()">
<option value="">Select City Name</option>
<!--populate value using php-->
<?php
$stmt ="SELECT * FROM Cities";
foreach ($con->query($stmt) as $row) {
?>
<option value="<?php echo $row['City_ID'];?>"><?php echo $row['City_Name'];?></option>
<?php
}
?>
</select>
</div>

<script>
function getArea(){
var c_city = $('#c_city').val();
$.ajax({
type: 'POST',
url: "get_area.php",
data: {c_city:c_city},
success: function(result){
//do something here with return value like alert
alert(result)
}
})
}
</script>

Then in your php script you can manipulate the value you receive from javascript

if(isset($_POST['c_city'])) 
{
$c_city = $_POST['c_city'];
echo $c_city;
}

Let me know if it helps or if you find a problem

Call php function with onclick event?

Just follow this code to achieve using jQuery ajax call.
This is the HTML code with jQuery included and I've used test.php file in the same directory. Just write your PHP function in test.php file. Finally the response will be displayed in the given div after the user pressed confirm.

<!DOCTYPE html>
<html>
<head>
<title>Jquery ajax</title>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
</head>
<body>
<button onclick="myFun()">Click me</button>
<div id="div1"></div>
<script>
function myFun(){
var r= confirm("Press a button!");
if (r==true)
{
$.ajax({url: "test.php", success: function(result){
$("#div1").html(result);
}});
}
else
{
alert("You pressed Cancel!");

}
}
</script>
</body>
</html>

How to call a PHP function from XMLHttpRequest (AJAX)?

What you need to do is make the PHP function run when the PHP file is triggered. To do this, add hello(); at the bottom of functions.php. To have multiple functions, you could have a folder of php files that all do one single function.

If you wanted to have a PHP file with multiple functions that the JS chooses, you could do something like this:

Functions.php

<?php

$function = $_POST["function"];

if ($function == "hello") {
hello();
}
else if ($function == "goodbye") {
goodbye();
}

function hello() {
echo "Hello from function php";
}

function goodbye() {
echo "Goodbye from function php";
}

?>

index.php


<script>

var xhr = new XMLHttpRequest();
xhr.open('POST','functions.php',true);
xhr.onload = function() {
console.log(this.responseText);
// If you wanted to call the function in here, then just make another whole xhr var and send it in this function
}

xhr.setRequestHeader('Content-type', 'application/x-www-form-urlencoded');
xhr.send('function=hello');
</script>

Eval could work, but it is an extremely bad idea to use it on data sent by the client (as in a malicious request could delete and read all sorts of data on the server)

Calling php function inside Javascript code

You can only do it by Making an AJAX request to a php page while passing in a parameter to initialise the function.

That means your AJAX will send in for example "functionName" to the php page "functionsListPage.php"

The GET will be recieved :

 if (isset($_GET['functionName']))
functionExec();

This is the only way so you are not calling direct from the client however you are indicating to the server you want to run a predefined request.

You cannot call a PHP function directly from the clientside.

Call any PHP function using a Javascript AJAX post request

The PHP Manual states that the $_POST super global variable only contains the post arguments for post data of type application/x-www-form-urlencoded or multipart/form-data.

An associative array of variables passed to the current script via the
HTTP POST method when using application/x-www-form-urlencoded or
multipart/form-data as the HTTP Content-Type in the request.

However, you are trying to send a post request with the body of type application/json.

To read a raw body in PHP you can do this:

$postdata = file_get_contents("php://input");

This will give you a string of the entire request body. You can then json_decode this string to get the desired JSON object.

As for the part of calling a function supplied in the request, the call_user_func_array will do the job fine. Whether or not that is something you should do is an entirely separate issue. From what I understand, you are edging on on the concept of a router and a controller.

I have writen a simple snippet of what I think you want to do:

<?php

switch ($_SERVER['REQUEST_METHOD']) {
case 'POST':
post_handler();
return;
case 'GET':
get_handler();
return;
default:
echo 'Not implemented';
return;
}

function post_handler() {
$raw_data = file_get_contents("php://input");
$req_body = json_decode($raw_data, TRUE);
call_user_func_array($req_body['function'], $req_body['args']);
}

function get_handler() {
echo 'This page left intentionally blank.';
}

function some_function($arg1, $arg2) {
echo $arg1.' '.$arg2;
}

?>

What is the difference between client-side and server-side programming?

Your code is split into two entirely separate parts, the server side and the client side.

                    |
---------->
HTTP request
|
+--------------+ | +--------------+
| | | | |
| browser | | | web server |
| (JavaScript) | | | (PHP etc.) |
| | | | |
+--------------+ | +--------------+
|
client side | server side
|
<----------
HTML, CSS, JavaScript
|

The two sides communicate via HTTP requests and responses. PHP is executed on the server and outputs some HTML and maybe JavaScript code which is sent as response to the client where the HTML is interpreted and the JavaScript is executed. Once PHP has finished outputting the response, the script ends and nothing will happen on the server until a new HTTP request comes in.

The example code executes like this:

<script type="text/javascript">
var foo = 'bar';
<?php
file_put_contents('foo.txt', ' + foo + ');
?>

var baz = <?php echo 42; ?>;
alert(baz);
</script>

Step 1, PHP executes all code between <?php ?> tags. The result is this:

<script type="text/javascript">
var foo = 'bar';

var baz = 42;
alert(baz);
</script>

The file_put_contents call did not result in anything, it just wrote " + foo + " into a file. The <?php echo 42; ?> call resulted in the output "42", which is now in the spot where that code used to be.

This resulting HTML/JavaScript code is now sent to the client, where it gets evaluated. The alert call works, while the foo variable is not used anywhere.

All PHP code is executed on the server before the client even starts executing any of the JavaScript. There's no PHP code left in the response that JavaScript could interact with.

To call some PHP code, the client will have to send a new HTTP request to the server. This can happen using one of three possible methods:

  1. A link, which causes the browser to load a new page.
  2. A form submission, which submits data to the server and loads a new page.
  3. An AJAX request, which is a Javascript technique to make a regular HTTP request to the server (like 1. and 2. will), but without leaving the current page.

Here's a question outlining these method in greater detail

You can also use JavaScript to make the browser open a new page using window.location or submit a form, emulating possibilities 1. and 2.



Related Topics



Leave a reply



Submit