Calling a particular PHP function on form submit
In the following line
<form method="post" action="display()">
the action should be the name of your script and you should call the function, Something like this
<form method="post" action="yourFileName.php">
<input type="text" name="studentname">
<input type="submit" value="click" name="submit"> <!-- assign a name for the button -->
</form>
<?php
function display()
{
echo "hello ".$_POST["studentname"];
}
if(isset($_POST['submit']))
{
display();
}
?>
calling php function from submit button
You are mixing PHP and JavaScript. If you want a pure PHP solution you could do something like:
<?php
if(isset($_POST['go'])){
$address = $_POST['address'];
echo $address;
}
?>
<form method="POST">
<input type="text" name="address">
<input type="submit" name="go" method="post">
</form>
With PHP once the form is submitted you can access form values with $_POST
so use $_POST['address']
instead of document.address.value
How to call php function on html form submit - in the same page
A very simple way to do is to do following :
yourpage.php
<?php
if(isset($_POST)){
//data posted , save it to the database
//display message etc
}
?>
<form method="post" action="yourpage.php" >....
Call a PHP function only when form submitted
First, give your input a name:
<input name="submit" value="Update">
Then in your code, assuming PHP 7+:
if ('Update' === ($_POST['submit'] ?? false)) {
wp_update_post($post, true);
}
How it works: when you click a button of type submit in the browser, the browser packages up the named input elements and sends them over the wire. The web server unravels the HTTP message and sends them to PHP, which makes them available in the associative array (aka dictionary) named $_POST
. (Or if the method is GET, then $_GET
). You can then check this array for the expected keys and their values.
As an aside, you don't strictly need to name your button. You could also do:
if (count($_POST)) {
...
}
which asserts there is at least one key value pair in the posted data.
You might also consider using var_dump('<pre>', $_POST)
as a diagnostic aid.
Finally, it's not clear to me where your $id
comes from, but that needs to be set properly, too.
my php function cant run when i call it in submit form
What you need to do is commented:-
<form method="POST" ><!-- remove onsubmit="sida()"-->
<textarea id="comment" placeholder="Write Your Comment Here....." name = "comment"></textarea><!-- add name attribute -->
<br>
<input type="text" id="username" placeholder="Your Name" name = "username"><!-- add name attribute -->
<br>
<input type="submit" value="Post Comment">
</form>
<div id="all_comments">
<?php
$data = array(); // define empty array
if(isset($_POST["comment"]) && isset($_POST["username"])){ // check with posted value not button value
$host="localhost";
$username="root";
$password="";
$databasename="vinhcv_truonghoc";
$i = 0; // DEFINE COUNTER
$connect=mysqli_connect($host,$username,$password,$databasename); // mysql_* is deprecated so use mysqli_* or PDO
if($connect){ // IF CONNECTION ESTABLISHED
$comment = mysqli_real_escape_string($connect,$_POST['comment']); // Prevent from SQL Injection
$username = mysqli_real_escape_string($connect,$_POST['username']); // Prevent from SQL Injection
$query = mysqli_query ($connect,"INSERT INTO comments (username,comment) VALUES ('".$username."','".$comment."')"); // check and change table name as well as column name
if($query){
echo "Inserted Successfully";
}else{
echo "Problem occur in insertion because of".mysqli_error($connect);
}
$comm = mysqli_query($connect,"select name,comment,post_time from comments order by post_time desc");
if($comm){ // IF QUERY EXECUTED
while($row=mysqli_fetch_array($comm)){
$data[$i]["name"] = $row['name']; // ASSIGN VALUES TO THE ARRAY
$data[$i]["comment"] = $row['comment'];
$data[$i]["time"] = $row['post_time'];
$i++;
}
}else{
echo "Query execution failed because of".mysqli_error($connect);
}
}else{
echo'connection problem because of'.mysqli_connect_error();
}
}else{
echo "All fields are need to fill properly";
}
?>
<?php foreach ($data as $dat){?> <!-- ITERATE THROUGH ARRAY -->
<div class="comment_div">
<p class="name">Posted By:<?php echo $data['name'];?></p>
<p class="comment"><?php echo $data['comment'];?></p>
<p class="time"><?php echo $data['time'];?></p>
</div>
<?php } ?>
</div>
Calling a PHP function from an HTML form in the same file
This cannot be done in the fashion you are talking about. PHP is server-side while the form exists on the client-side. You will need to look into using JavaScript and/or Ajax if you don't want to refresh the page.
test.php
<form action="javascript:void(0);" method="post">
<input type="text" name="user" placeholder="enter a text" />
<input type="submit" value="submit" />
</form>
<script type="text/javascript">
$("form").submit(function(){
var str = $(this).serialize();
$.ajax('getResult.php', str, function(result){
alert(result); // The result variable will contain any text echoed by getResult.php
}
return(false);
});
</script>
It will call getResult.php
and pass the serialized form to it so the PHP can read those values. Anything getResult.php
echos will be returned to the JavaScript function in the result
variable back on test.php
and (in this case) shown in an alert box.
getResult.php
<?php
echo "The name you typed is: " . $_REQUEST['user'];
?>
NOTE
This example uses jQuery, a third-party JavaScript wrapper. I suggest you first develop a better understanding of how these web technologies work together before complicating things for yourself further.
Call PHP Function from Action Form
You can't call PHP functions directly. However, if the php file is formatted how you displayed here with only two functions you could pass a flag in as a POST field and have a logic block determine which function call based on that flag. It's not ideal but it would work for your purposes. However, this would force the page to refresh and you would probably have to load a different page after the function returns so you may want to simply implement this as an ajax call to avoid the page refresh.
Edit based on your comment (Using jQuery Ajax):
I am using the .ajax() jQuery function. My intentions create one php file that contains multiple functions for different html forms. – tmhenson
Well in this case, you can have your file contain the logic block to "route" the request to the right function and finally return the result.
I'll try to provide an option for what you want to do based on some simple jQuery. Say you have something like this:
Java Script:
$("#button1").click(function(e){
e.preventDefault(); // prevents submit event if button is a submit
ajax_route('ap');
});
$("#button2").click(function(e){
e.preventDefault(); // prevents submit event if button is a submit
ajax_route('se');
});
function ajax_route(action_requested){
$.post("ajax_handler.php", {action : action_requested}, function(data){
if (data.length>0){
alert("Hoorah! Completed the action requested: "+action_requested);
}
})
}
PHP (inside ajax_handler.php)
<?php
// make sure u have an action to take
if(isset($_POST['action'])
switch($_POST['action']){
case 'ap': addPerson(); break;
case 'se': sendEmail(); break;
default: break;
}
}
function addPerson() {
//do stuff here
}
function sendEmail() {
//do some stuff here
}
?>
how to call a PHP function with HTML button click?
Like this?
<?php
if (isset($_POST['submit'])) {
someFunction();
}
function someFunction() {
echo 'HI';
}
?>
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>Document</title>
</head>
<body>
<form action="" method="POST">
<input type="submit" name="submit">
</form>
</body>
</html>
Although quite weird, this will work, you can use $_GET
if you want
Related Topics
How to Catch a "Catchable Fatal Error" on PHP Type Hinting
Scaling a Chat App - Short Polling VS. Long Polling (Ajax, PHP)
How to Get Previous Month and Year Relative to Today, Using Strtotime and Date
Best Way to Process Large Xml in PHP
Magic _Get Getter for Static Properties in PHP
How to Solve General Error: 2006 MySQL Server Has Gone Away
Extra Backslash Needed in PHP Regexp Pattern
Simple PHP Contact Form with Firebase Hosting
Having Problems While Try to Install Oauth with Pecl in Mamp on MAC Os Lion
Convert Month from Name to Number
How to Send a Status Code in PHP, Without Maintaining an Array of Status Names