I've searched around a lot of topics, but couldn't find the answer. My goal is to have a HTML hyperlink calling a Javascript AJAX post request on a PHP page to run a PHP function (optionally with any amount of arguments). A lot of topics solved this problem for defined functions (with a specific name). I want to generalize the AJAX post request function in order to pass the PHP function name to the AJAX request to call it, so I can define in Javascript what PHP function to call.
This is what I have, but it goes wrong at the PHP script...
The HTML:
<a onclick="call_php('php_function_name', ['arg_1', 'arg_2']);">call</a>
<p id="demo"></p>
The Javascript:
function call_php(fname, args) {
var xhttp = new XMLHttpRequest();
xhttp.onreadystatechange = function () {
if (this.readyState == 4 && this.status == 200) {
document.getElementById('demo').innerHTML = this.responseText;
}
};
xhttp.open('POST', 'includes/functions.php', true);
xhttp.setRequestHeader('Content-type', 'application/json');
xhttp.send(JSON.stringify({
'fname': fname,
'args': args
}));
}
At the Javascript I'm questioning the JSON.stringify()
and setRequestHeader()
if it is used correctly in this case.
The PHP, which should call a function in it's file:
if ($_SERVER['REQUEST_METHOD'] === 'POST') {
//header('Content-Type: application/json');
$post = json_decode($_POST/*, true*/);
// DO SOMETHING TO CALL: fname(...args);
}
function php_function_name(arg_1, arg_2) {
// A FUNCTION...
}
At the PHP I'm questioning the header('Content-Type: application/json')
since it's already defined at the Javascript. But the main question is: how to write the PHP code to call the PHP function? By the way: when I print echo $post
it gives a warning: json_decode() expects parameter 1 to be string, array given...