开发者

How to call php function from button?

I've got an easy php script :

<?php
    $command = "git pull";
    $output = shell_exec($command);
    echo "<pre>$output</pre>";
?>

And I want to call it by pressing button :

<form metod="post" action="/pull.php">
   <button type="submit">Pull changes</button>
</form>

And I want to ge开发者_StackOverflow中文版t output right under the button or replace button with output but I don't want to go to /pull.php I just want to run script and get output. How can I make it ?


You need to use javascript's XMLHTTPRequest (or better yet jQuery's get), in either case JavaScript will let you load content dynamically from another url.


To use ajax to get the response and display it below the button, first make space for the message below the button:

 <form onclick='run()'>
 <button type="submit">Pull changes</button>
 <div id='msg'><div/>
 </form>

now in the header tag add the following:

 <script type="text/javascript">
 function run()
 {
 loadXMLDoc("pull.php",function()
 {
    if (xmlhttp.readyState==4 && xmlhttp.status==200)
    {
    document.getElementById('msg') = xmlhttp.responseText;
    }
 });
 }
 function loadXMLDoc(url,cfunc)
 {
 if (window.XMLHttpRequest)
   {// code for IE7+, Firefox, Chrome, Opera, Safari
   xmlhttp=new XMLHttpRequest();
   }
 else
   {// code for IE6, IE5
   xmlhttp=new ActiveXObject("Microsoft.XMLHTTP");
   }
 xmlhttp.onreadystatechange=cfunc;
 xmlhttp.open("POST",url,true);
 xmlhttp.send();
 }
 </script>


PHP is a server-side language and clicking a button is a client-side action, thus you'll need to use a client-side solution like JavaScript to bridge the gap.


leave the action property empty and put that code right after the button, you'll have something like:

<form metod="post" action="">
    <button name="button" type="submit">Pull changes</button>
</form>

<?php
    if(isset($_POST['button'])) {
        $command = "git pull";
        $output = shell_exec($command);
        echo "<pre>$output</pre>";
    }
?>
0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜