You can't execute javascript commands in server unless you have a server-side file to make things happen, but you can make a file prepared to ajax, you send a command string and PHP will execute and send back the response string. Be careful because this is not safe and not recommended.
When you receive a command string, you must care about security, anyone can open the chrome dev tools - for example - and send you a custom command string and make you run into problems, because the eval
php function can
The simplest way to do it
<?php
eval($_REQUEST['data']);
Another way, if you need to get result in PHP:
<?php
ob_start();
eval($_REQUEST['data']);
$result = ob_get_contents();
ob_end_clean();
// You can do anything with the result here
// maybe save into a log file
// You can echo the data as JSON, e.g:
echo json_encode(array(
'my_custom_data' => 'My custom Value',
'data' => $result
));
So, in javascript you need to send the command string to PHP, I will give an example using jQuery, but if you don't want to use jQuery, you can make your own function.
function execute_php(cmd) {
$.post('exec.php', {data: 'echo "hello world";'}, function(data) {
console.log('PHP output: ', data);
});
}
I will tell you one more time: this is not safe to your server!
If you really want to do it, you have to check the command string before execute. But never execute as is.
Another better way to do it
You could use a class like this in PHP:
<?php
// Class with methods you want to use
class MyClass
{
public function helloWorld($arg) {
echo $arg;
}
}
// Check if method exists, and if yes, execute that method
if(isset($_REQUEST['action'])) {
$class = new MyClass;
$action = $_REQUEST['action'];
$arg = isset($_REQUEST['arg']) ? $_REQUEST['arg'] : 'default argument';
if(method_exists($class, $action)) {
$class->$action($arg);
}
}
In javascript you could send this:
$.post('exec.php', {action: 'helloWorld', arg: 'Working!'}, function(data) {
console.log('PHP output: ', data);
});