问题
I want to run a php function on button click. for eg :
<input type="button" name="test" id="test" value="RUN" onclick="<?php echo testfun(); ?>" /><br/>
<?php
function testfun()
{
echo "Your test function on button click is working";
}
?>
My question is that when I do this I don't get the expected output I was looking for. Please give me the best solution for this to run a php function on button click whether it is a simple button
or submit
.
回答1:
I tried the code of William, Thanks brother.
but it's not working as a simple button I have to add form with method="post". Also I have to write submit instead of button.
here is my code below..
<form method="post">
<input type="submit" name="test" id="test" value="RUN" /><br/>
</form>
<?php
function testfun()
{
echo "Your test function on button click is working";
}
if(array_key_exists('test',$_POST)){
testfun();
}
?>
回答2:
Do this:
<input type="button" name="test" id="test" value="RUN" /><br/>
<?php
function testfun()
{
echo "Your test function on button click is working";
}
if(array_key_exists('test',$_POST)){
testfun();
}
?>
回答3:
You are trying to call a javascript function. If you want to call a PHP function, you have to use for example a form:
<form action="action_page.php">
First name:<br>
<input type="text" name="firstname" value="Mickey">
<br>
Last name:<br>
<input type="text" name="lastname" value="Mouse">
<br><br>
<input type="submit" value="Submit">
</form>
(Original Code from: http://www.w3schools.com/html/html_forms.asp)
So if you want do do a asynchron call, you could use 'Ajax' - and yeah, that's the Javascript-Way. But I think, that my code example is enough for this time :)
回答4:
<a href="home.php?click=1" class="btn">Click me</a>
<?php
if($_GET['click']){
doSomething();
}
?>
But is better to use JS and with ajax to call function!
回答5:
No Problem You can use onClick()
function easily without using any other interference of language,
<?php
echo '<br><Button onclick="document.getElementById(';?>'modal-wrapper2'<?php echo ').style.display=';?>'block'<?php echo '" name="comment" style="width:100px; color: white;background-color: black;border-radius: 10px; padding: 4px;">Show</button>';
?>
回答6:
You can use isset()
.
<form method="post">
<input type="submit" name="test" id="test" value="RUN" />
</form>
<?php
function testfun()
{
echo "Your test function on button click is working";
}
if(isset($_POST('submit')))
{
testfun();
}
?>
来源:https://stackoverflow.com/questions/32824360/run-php-function-on-button-click