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

3 Answers 3

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";
?>
Sign up to request clarification or add additional context in comments.

9 Comments

Using document.write() after the page is loaded will wipe out the page.
@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.
how Instead welcome.php i use from <?php ?> in html file?
@آهومحمدیان 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.
What to write here action="?" I do not want to use welcome.php
|
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";
  } 
?>

Comments

-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

9 Comments

why to do such a costly operation like submitting a form just for an onClick ??
@RohitasBehera the answer in the duplicate question you tagged is also a form submit.
I was just asking :( .... & no I dint votedown
how Instead welcome.php i use from <?php ?> in html file?
php is server side code, it has to be triggered from the server, not the browser.
|