简体   繁体   中英

Launch PHP function when button is pressed

I have a php function that writes some text to a local file...

<?php
 function createtextfile() 
 {
 $file = fopen("test.txt","w");
echo fwrite($file,"Hello World. Testing!");
fclose($file);
}
?>

I am trying to launch this when a button is clicked but am not sure how best to go about it. Would I need to use javascript or is there a way I can do it purely with PHP?

Move createfile to a new php file and call the php file with ajax

<a href="#" id="btn">Button</a>
<script>
    $("#btn").click(function(e) {
        $.ajax("createtextfile.php");
        e.stopPropagation();
        return false;
    });
</script>

and inside createfile.php

$file = fopen("test.txt","w");
fwrite($file,"Hello World. Testing!");
fclose($file);

You can do it purely using PHP and HTML if you make the button part of a form, and send POST / GET variables, then look for them in the PHP script;

i.e.

<?php
  if($_POST['submit'] == "Push Button!"){
    //Do whatever  
  }else{
    //Show the regular webpage.
?>

<form id="someForm" method="POST">
  <input type="submit" id="submit" value="Push Button!">
</form>

<?php
}
?>

假装您正在制作HTML表单,并让您的php作为提交时调用的操作。

if you use a form it becomes really easy

your html would look something like

<form method="GET/POST" action="yourphpscript.php">

whatever you wanna include in the form

<input type="submit" name="submit" value="submit"/>

</form>

then using php you can do what you need to, once you find out the button is clicked

<?php

      if(isset($_POST['submit']))
      {
            do what you wanna do in here
      }

?>

This is the php way of doing things, not too sure about javascript

Hope this helps.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM