Php button action event needed - php

How do i implement button click php when either one of the buttons is clicked? I am trying to do is, if sumbit button is clicked the php script below shows it written to a file and if view comments is hit shows comments
<html>
<body>
<form action="http://localhost/class/assignment10.php" method="post">
User Name: <input type="text" name="uname"><br>
User Comments: <textarea type ="text" name="tcomment"></textarea><br>
<input type="submit" value="Submit Comments"/>
<input type="submit" value="View Comments"/>
</form>
</body>
</html>
I have two form buttons IF submit comments is clickedthe php code should write the user’s name and comments to a text file (use fputs function to write to a file. Also you should insert a newline after each name and each comment). When user’s name and comments are successfully recorded, php should direct
On the other hand, if a user clicks on the ‘view all comments’ button, the php code should
show all users and their corresponding comments (use fgets function)
<html>
<head>
<title>PHPLesson10</title>
</head>
<body>
<?php
// Collect user name and add a line break at the end.
$customer = $_POST['uname']."\n";
// Collect comment and add a line break.
$comments = $_POST['tcomment']."\n";
$file = fopen("C:/data/feedback.txt", "a");
If ($file) // if the file open successfully
{
// Write the variables to the file.
fputs($file, $customer);
fputs($file, $comments);
fclose($file);
}
Else
{
Echo "Please try again.";
}
?>
</body>
</html>
<?php
// Open the file feedback for reading
$file = fopen("C:/data/feedback.txt", "r");
// While the end of the file has NOT reached
While (!feof($file))
{
// Print one line of file
Echo fgets($file);
Echo "<br />";
}
// close the connection
fclose($file);
?>

Your submit buttons should like below :
<input type="submit" name="submit_comment" value="Submit Comments"/>
<input type="submit" name="view_comment" value="View Comments"/>
And your php code for each buttons should like below:
<?php
if(isset($_POST['submit_comment']))
{
//the php code will be here for save comment
}
if(isset($_POST['view_comment']))
{
//the php code will be here for view comment
}
?>

use name attribute on buttons
<input type="submit" value="Submit Comments" name="btn_submit"/>
<input type="submit" value="View Comments" name="btn_view"/>
then on php you can check something like
if (isset($_POST['btn_submit']))...
or
if (isset($_POST['btn_view']))...
Best regards,
Nebojsa

For buttons, I usually use <button> tags and not <input> tags, as long as you're using <!doctype html> for HTML5.
<form action="http://localhost/class/assignment10.php" method="post" id="commentForm">
<button type="submit" name="action" value="submit" form="commentForm">
Submit Comments
</button>
<button type="submit" name="action" value="view" form="commentForm">
View Comments
</button>
</form>
Then use PHP to figure out what the user clicked like this:
<?php
$action = $_POST["action"];
if ($action == "submit") {
// submission code
}
if ($action == "view") {
// viewing code
}
else {
die("Your request could not be completed.");
}
?>

First give your submit buttons a name like so:
<input type="submit" name="button1" value="Submit Comments"/>
<input type="submit" name="button2" value="View Comments"/>
and then use this PHP:
<?php
if (isset(#$_POST['button1'])) {
//Code to execute
}
if (isset(#$_POST['button2'])) {
//Code to execute
}
?>

Related

submit data via URL bar in PHP and HTML

I have this very basic form in my html page.
<form action="post.php" method="post">
Message: <input type="text" name="message" />
<input type="submit" name="submit" value="send">
</form>
and then stores the data onto my database backend.
id also want to submit data via URL bar, such as this.
http://localhost/test.php?message=test&submit=send
but when i try to do above, nothing happens.
how can i achieve such method?
[EDIT]
my post.php
<?php
include_once("connect.php");
if (isset($_GET['submit'])) {
if ($_GET['message'] == "") {
echo " no input, return";
exit();
}
else {
$message = $_GET['message'];
mysql_query("insert into data (message) values ('$message')");
header ('location:index.php');
exit ();
}
}
else {
echo "invalid";
}
?>
use GET method instead of POST
so your code should be like follow:
<form action="post.php" method="GET">
Message: <input type="text" name="message" />
<input type="submit" name="submit" value="send">
</form>
and in the post.php you can get those Query string by using $_GET['message'] or $_REQUEST['message']
use a form GET method. to submit data of a form as a query string.
<form action="test.php" method="GET">

PHP form - on submit stay on same page

I have a PHP form that is located on file contact.html.
The form is processed from file processForm.php.
When a user fills out the form and clicks on submit,
processForm.php sends the email and direct the user to - processForm.php
with a message on that page "Success! Your message has been sent."
I do not know much about PHP, but I know that the action that is calling for this is:
// Die with a success message
die("<span class='success'>Success! Your message has been sent.</span>");
How can I keep the message inside the form div without redirecting to the
processForm.php page?
I can post the entire processForm.php if needed, but it is long.
In order to stay on the same page on submit you can leave action empty (action="") into the form tag, or leave it out altogether.
For the message, create a variable ($message = "Success! You entered: ".$input;") and then echo the variable at the place in the page where you want the message to appear with <?php echo $message; ?>.
Like this:
<?php
$message = "";
if(isset($_POST['SubmitButton'])){ //check if form was submitted
$input = $_POST['inputText']; //get input text
$message = "Success! You entered: ".$input;
}
?>
<html>
<body>
<form action="" method="post">
<?php echo $message; ?>
<input type="text" name="inputText"/>
<input type="submit" name="SubmitButton"/>
</form>
</body>
</html>
The best way to stay on the same page is to post to the same page:
<form method="post" action="<?=$_SERVER['PHP_SELF'];?>">
There are two ways of doing it:
Submit the form to the same page: Handle the submitted form using PHP script. (This can be done by setting the form action to the current page URL.)
if(isset($_POST['submit'])) {
// Enter the code you want to execute after the form has been submitted
// Display Success or Failure message (if any)
} else {
// Display the Form and the Submit Button
}
Using AJAX Form Submission which is a little more difficult for a beginner than method #1.
You can use the # action in a form action:
<?php
if(isset($_POST['SubmitButton'])){ // Check if form was submitted
$input = $_POST['inputText']; // Get input text
$message = "Success! You entered: " . $input;
}
?>
<html>
<body>
<form action="#" method="post">
<?php echo $message; ?>
<input type="text" name="inputText"/>
<input type="submit" name="SubmitButton"/>
</form>
</body>
</html>
Friend. Use this way, There will be no "Undefined variable message" and it will work fine.
<?php
if(isset($_POST['SubmitButton'])){
$price = $_POST["price"];
$qty = $_POST["qty"];
$message = $price*$qty;
}
?>
<!DOCTYPE html>
<html>
<head>
<title></title>
</head>
<body>
<form action="#" method="post">
<input type="number" name="price"> <br>
<input type="number" name="qty"><br>
<input type="submit" name="SubmitButton">
</form>
<?php echo "The Answer is" .$message; ?>
</body>
</html>
You have to use code similar to this:
echo "<div id='divwithform'>";
if(isset($_POST['submit'])) // if form was submitted (if you came here with form data)
{
echo "Success";
}
else // if form was not submitted (if you came here without form data)
{
echo "<form> ... </form>";
}
echo "</div>";
Code with if like this is typical for many pages, however this is very simplified.
Normally, you have to validate some data in first "if" (check if form fields were not empty etc).
Please visit www.thenewboston.org or phpacademy.org. There are very good PHP video tutorials, including forms.
You can see the following example for the Form action on the same page
<form action="" method="post">
<table border="1px">
<tr><td>Name: <input type="text" name="user_name" ></td></tr>
<tr><td align="right"> <input type="submit" value="submit" name="btn">
</td></tr>
</table>
</form>
<?php
if(isset($_POST['btn'])){
$name=$_POST['user_name'];
echo 'Welcome '. $name;
}
?>
simple just ignore the action attribute and use !empty (not empty) in php.
<form method="post">
<input type="name" name="name">
<input type="submit">
</form>
<?PHP
if(!empty($_POST['name']))
{
echo $_POST['name'];
}
?>
Try this... worked for me
<form action="submit.php" method="post">
<input type="text" name="input">
<input type="submit">
</form>
------ submit.php ------
<?php header("Location: ../index.php"); ?>
I know this is an old question but since it came up as the top answer on Google, it is worth an update.
You do not need to use jQuery or JavaScript to stay on the same page after form submission.
All you need to do is get PHP to return just a status code of 204 (No Content).
That tells the page to stay where it is. Of course, you will probably then want some JavaScript to empty the selected filename.
What I do is I want the page to stay after submit when there are errors...So I want the page to be reloaded :
($_SERVER["PHP_SELF"])
While I include the sript from a seperate file e.g
include_once "test.php";
I also read somewhere that
if(isset($_POST['submit']))
Is a beginners old fasion way of posting a form, and
if ($_SERVER['REQUEST_METHOD'] == 'POST')
Should be used (Not my words, read it somewhere)

how to send $_POST by a form?

hello i have problems sending an id in a form.
the structure of the site is:
session_start();
if (!isset($_SESSION['a'])){
...create the session from some variables...
$_SESSION['a'] = $var;
$var = $_SESSION['a'];
}else{
$var = $_SESSION['a'];
if (isset($_POST["one"]) ){
echo "post one was send";
}
if (isset($_POST["two"]) ){
echo "post en was send";
}
echo "session already exists.";
}
the form where it will be send is placed at the end of the page and will be embedded into html by an excluded php:
echo '...
<ul class="drop_down">
<form action="'.$_SERVER['PHP_SELF'].'" method="post">
<input type="submit" id="one" name="one" value="one"/><div>set one</div>
</form>
<form action="'.$_SERVER['PHP_SELF'].'" method="post">
<input type="submit" id="two" name="two" value="two"><div>set two</div>
</form>
</ul>
...';
so the strange about that is, that the form not seems to be send because the first part of the code works as it should do just the else part does not work when sending the form. it just will be displayed the echo text below the conditions for post-method.
so if there is someone who could tell how i can solve this i really would apreciate.
thanks alot.
UPDATE:
okay, using the request-method without action makes echo out the message. i thought it will work.
now the problem is, that when i will send the post the session should have been changed. this is not the case and i have no clue why this is not working.
so the original code is like that:
if (isset($_POST["tr"]) ){
$_SESSION['a'] = "tr";
echo "post tr was send and session has changed to tr";
}
If you have a forms like this
<form method="post">
<input type="submit" value="Submit Form" name="formA">
</form>
<form method="post">
<input type="submit" value="Submit Form" name="formB">
</form>
Then you can check like this
if (isset($_REQUEST['formA']) ...
elseif (isset($_REQUEST['formB']) ...

Edit XML via HTML Form (PHP)

I'm trying to create a form that will let you edit the contents of an xml tag. i currently have a form.php:
<?php
$data=simplexml_load_file('welcome.xml');
$welcome=$data->item->name;
?>
<form method="post">
<textarea name="name"><?php echo $welcome ?></textarea>
<br>
<input type="submit" name="submit" value="submit">
</form>
<?php
if(isset($_POST['submit'])) {
$data=simplexml_load_file('welcome.xml');
$data->item->name=$_POST['name'];
$handle=fopen("welcome.xml","wb");
fwrite($handle,$xml->asXML());
fclose($handle);
}
?>
and welcome.xml:
<welcome>
<item>
<name>$welcome</name>
</item>
</welcome>
when i press submit it doesn't save what's entered, it just refreshes the page and deletes whatever the value in the xml file was before..
UPDATE
The form works now, but I've added a reset button, i need it to clear the xml file so it only has the <welcome> tags. I've changed $data->item->name=$_POST['welcome']; to $data=''; but it deletes the text and keeps the tags still.
You can do it with simplexml.
To read data from xml:
$data = simplexml_load_file('welcome.xml');
$welcome = $data->item[0]->name;
And to write data:
$data = simplexml_load_file('welcome.xml');
$data->item[0]->name = $_POST['welcome'];
$handle = fopen("welcome.xml", "wb");
fwrite($handle, $xml->asXML());
fclose($handle);
EDIT:
For the question in the comment:
<?php
if(isset($_POST['submit'])) {
$data=simplexml_load_file('welcome.xml');
$data->item->name=$_POST['name'];
$handle=fopen("welcome.xml","wb");
fwrite($handle,$data->asXML());
fclose($handle);
}
$data=simplexml_load_file('welcome.xml');
$welcome=$data->item->name;
?>
<form method="post">
<textarea name="name"><?php echo $welcome ?></textarea>
<br>
<input type="submit" name="submit" value="submit">
</form>

Button Click Counter in PHP

I'm trying to build a tiny skeleton framework for a friend, where each time a button is pressed a certain animation is played. He wants a way to count the number of times the button is clicked, as well, but I can't seem to get that part working. What am I doing wrong?
<?php
if( isset($_POST['mushu']) )
{
echo "Working.";
playAnimation();
clickInc();
}
function playAnimation()
{
/* ... */;
}
function clickInc()
{
$count = ("clickcount.txt");
$clicks = file($count);
$clicks[0]++;
$fp = fopen($count, "w") or die("Can't open file");
fputs($fp, "$clicks[0]");
fclose($fp);
echo $clicks[0];
}
?>
<html>
<head>
<title>Adobe Kitten</title>
</head>
<body>
<form action="<?php $_SERVER['PHP_SELF']; ?>">
<input type="button"
value="Let's see what Mushu is up to."
name="mushu">
</form>
</body>
</html>
<form action="<?php $_SERVER['PHP_SELF']; ?>" method="post">
<input type="submit"
value="Let's see what Mushu is up to."
name="mushu">
</form>
First of all use the form with method="post", or change $_POST[] to $_GET[] in your Script.
And If your Button is not a Submit button, then you are not submitting the form. So I've changed type="button" to type="submit".
Should work
The code looks fine, I tested it and it worked for me.
I suggest:
Make sure the file isn't read-only.
Make sure the file is called "clickcount.txt"
Make sure it's in the same folder as your script.
It would be helpful to know the error but a shot in the dark - it could be a problem with Write permissions?
also, change to:
<input type="submit" value="Let's see what Mushu is up to." name="mushu" />

Categories