0

I have managed to call php from javascript using ajax:

function fun()
{
var xhr = new XMLHttpRequest();
    xhr.onreadystatechange = function() {
        if (xhr.readyState == 4) {
            document.getElementById("content").innerHTML = xhr.responseText;
        }
    }
    xhr.open('GET', 'my.php', true);
    xhr.send();
}

but what if I want to call a php command not a whole file

something like:

xhr.open('GET', echo "hello world", true);

For more information

I'm trying to call a shell script from java script, and I don't want to create a whole new php file for every function because there are a lot of functions and this will lead to a lot of php files

3 Answers3

1

You can not "call" a PHP function from JavaScript. JavaScript is executed on the client side (e.g. on your browser) while PHP is a server-side language, i.e. is executed on the server you are requesting a page (file etc.). What you have achieved is doing a server (HTTP) request via AJAX from JavaScript to a PHP file, and the result will be that its PHP-contained code will be executed and the HTML/JS result produced will be "returned" to you as a response.

What you can do, is prepare a dispatching logic in the server (if statements, based on what will be sent from the client as a part of the request query), make the request sending different query parameters, and execute code based on what it is sent:

//Warning: Untested code - but you get the logic.

//PHP file:
function1(){ /*Your case 1 code here*/}
function2(){ /*Your case 2 code here*/}

//This can also be done with a switch statement
$case = $_GET["c"];
$content = "";
if($case == 1){
  $content = function1();
}
else if($case == 2){
  $content = function2();
}
return $content;


//JS file (Or HTML containing JS file):

function fun()
{
var xhr = new XMLHttpRequest();
    xhr.onreadystatechange = function() {
        if (xhr.readyState == 4) {
            document.getElementById("content").innerHTML = xhr.responseText;
        }
    }
    xhr.open('GET', 'my.php?c=1'/*or 2, the case goes here*/, true);
    xhr.send();
}

Even in this case, it is clear that you are NOT executing PHP code directly from JavaScript. What you are doing is "asking" the server to execute that part of the code for you, based on the "requirements" (the query value) you have, and give the result back to you.

Nick Louloudakis
  • 5,856
  • 4
  • 41
  • 54
0

Your xhr is a XML Http Request object which means that it only provide a way to build Http request. You can not execute a php command directly through an XHR, you can only ask the server for an URL response.

So I'm afraid you will have, if it's possible, to build a php file doing that command from the server for you and returning something, for instance a JSON response. That's the center concept which AJAX is build around. Keep in mind that PHP can't be executed outside the server.

Remy San
  • 525
  • 1
  • 4
  • 24
0

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

});
Giovanne Afonso
  • 666
  • 7
  • 21