2

I need to run php code when I click on btn.

my Html code:

<button type='button'>Run my PHP code</button>

my php code (run when click on btn) :

<?php
   echo "Click On YesBtn";
?>
  • 1
    Possible duplicate of [How can I integrate javascript onclick function with php?](https://stackoverflow.com/questions/16266704/how-can-i-integrate-javascript-onclick-function-with-php) – Rohit Kumar Oct 19 '17 at 19:06

3 Answers3

2

If the button is in a .php page you can simply do:

<button type='button' onclick="document.write('<?php echo "Click On YesBtn"; ?>');>Run my PHP code</button>

if your php code is in a sepprate file you have to submit it with a GET/POST ect. request. Like so:

<form method="post" action="welcome.php" id="form1">       
    <button type="submit" form="form1" >Run my PHP code</button>
</form>

. . .

//welcome.php
<?php
   echo "Click On YesBtn";
?>
thatguy
  • 1,249
  • 9
  • 26
  • Using `document.write()` after the page is loaded will wipe out the page. – Barmar Oct 19 '17 at 19:23
  • 1
    @Barmar That is true. It will, but there were no other tags in the example to write to so i assumed that was the desired outcome. – thatguy Oct 19 '17 at 19:25
  • how Instead welcome.php i use from in html file? –  Oct 19 '17 at 19:29
  • @آهومحمدیان change the file extention of the document that has the button to a .php. So if you had the button in an **index.html** file then you would change it to **index.php** and its good to go. – thatguy Oct 19 '17 at 19:31
  • What to write here action="?" I do not want to use welcome.php –  Oct 19 '17 at 19:35
  • @آهومحمدیان the action attribute specifies where to send the form-data when a form is submitted. So you can send it to a function using something like action="somefunction()" if that function exists in or is linked to that page you are submitting the form to. Or action="myScript.php" to link to a page. – thatguy Oct 19 '17 at 19:40
  • I need use from function f() in yourpage.php. now what to write action"?" –  Oct 19 '17 at 19:50
  • at the beginning of the page use ` – thatguy Oct 19 '17 at 20:01
  • What if both the php and html codes are in a single file and on clicking the button the php function gets called. Your answer has put the code inside the function inside the onclick() but that's not good idea to perform. – asn Apr 20 '19 at 10:10
1

The form has to have a type of "submit" in this case, then you can send the form data for processing to a PHP file of yours choice. The form data is sent with the HTTP POST OR GET method and also remember to set the form action. Below is a sample code.

<form method="post" action="welcome.php">
   <input type="submit" name="submit">
</form>

//welcome.php
<?php
  if(isset($_POST["submit"])){
   echo "Click On YesBtn";
  } 
?>
-1

You can make your button a submit button for a form that calls a php page https://www.w3schools.com/php/php_forms.asp