Call php function on button click

I am trying to call a php function on a button click using Javascript. It doesn't seem to work fine.

Is there a better way to call php function on button click

<!DOCTYPE html>
<html>

<head>
<script type="text/javascript">
function executeShellScript(clicked)
{
    var x="<?php ex(); ?>";
    alert(x);
    return false;
}
</script>
</head>

<body>


<input type="button" id="sample" value="click" onclick="executeShellScript()"/>

<?php

ini_set('display_errors',1);
ini_set('display_startup_errors',1);
error_reporting(-1);

function ex(){

echo "Trying to run shell script from the web browser";
echo "<br>";

$contents = file_get_contents('/var/www/shellscriptphp/helloworld.sh');
echo shell_exec($contents);

$result = shell_exec('sh /var/www/shellscriptphp/helloworld.sh');
echo $result;
}

?>

</body>
</html>

      

+3


source to share


1 answer


You cannot call a php function in the same way as you explained above. As the php script execution happens before the web page source is sent to the client browser from the server.

However, you can do it with an ajax call where you call a client side js function on a button and this inturn function makes a server side ajax call and returns the result.

Example:



Here is some sample code you might relate to. This page makes a POST ajax request to itself and returns a response. Let me know you are wrong as I cannot get it to run here.

<?php
/** this code handles the post ajax request**/
if(isset($_POST['getAjax'])) {

    /* you can do this below settings via your php ini also. no relation with our stuff */
    ini_set('display_errors',1);
    ini_set('display_startup_errors',1);
    error_reporting(-1);

    /* setting content type as json */
    header('Content-Type: application/json');
    $result = shell_exec('sh /var/www/shellscriptphp/helloworld.sh');       
    /* making json string with the result from shell script */
    echo json_encode(array("result"=>$result));
    /* and we are done and exit */
    exit();
}
?>

<!DOCTYPE html>
<html>
<head>
<script src="https://code.jquery.com/jquery-2.1.1.js" type="text/javascript"></script>
<script type="text/javascript">
function executeShellScript(clicked)
{
    //$_SERVER["REQUEST_URI"] is used to refer to the current page as we have the ajax target as this same page
    $.post('<?PHP echo $_SERVER["REQUEST_URI"]; ?>',{"getAjax":true}, function(data) {
        alert(data['result']);
        return false;
    });


}
</script>
</head>
<body>
<input type="button" id="sample" value="click" onclick="executeShellScript()"/>
</body>
</html> 

      

+3


source







All Articles