PHP form - on submit stay on same page - php

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)

Related

How can I write the data entered in a form to a text file on button click?

I'll preface this with I'm not a coder nor aspiring to become one.
I just want to play around with something simple.
Please don't feel bad about spoon-feeding me here haha.
All I want is when I hit a my submit button the text entered in the text field is saved to a file called log.text
I want it to overwrite each time.
Once data has been written I want it to redirect to another page.
Tried this but it doesn't create the file nor write to it even if I create it manually. The redirect also doesn't work because I'm an idiot.
Any help guys? :(
<?php
$email = $_REQUEST['email'];
$file = fopen("log.txt","a+");
fwrite($file,$email);
print_r(error_get_last());
header("Location: http://www.example.com/");
?>
<form action= "" method="post" name="form">
<input type="text" name="email">
<br>
<br>
<input type="submit" name="submit" value="submit"><br>
</form>
It is because the action element of the form is empty.
It should be \n
<form action="action.php(or any other php file that is handling the form)" method="post" name="form">
This guide offered me the solution I was after.
Thanks anyway guys!
http://www.howtoplaza.com/save-web-form-data-text-file
Because you dint checked whether the form is submitted or not. if submited create log. code given below
<?php
if(isset($_REQUEST['submit']))// if to check whether submit name is passed or not
{
$email = $_REQUEST['email'];
$file = fopen("log.txt","a+");
fwrite($file,$email);
print_r(error_get_last());
header("Location: http://www.example.com/");
}
?>
<html>
<form action= "" method="post" name="form">
<input type="text" name="email">
<br>
<br>
<input type="submit" name="submit" value="submit"><br>
</form>
</html>

HTML Button that saves and move to the next page

I have a small problem. I want to have a button in my html page that saves every data that is added in the textfields and also when I click it to move to the next page.
My code is the follow...
<input type=button onClick="location.href='education.php'" value='Next'>
but it only moves to next page it does not save the data in the database ...
Can you help me please?
Thanks.
Remove the JavaScript
Change the type to submit
Wrap it in a <form>
Set the action of the form to education.php
Set the method of the form to post
Then, in education.php, read the data from $_POST and use PDO (with bound variables) to insert it into the database.
Try this :
<?php
if(isset($_POST['submit']))
{
// Insert Query Put here
header('Location: education.php');
}
?>
<html>
<head>
</head>
<body>
<form action="<?php echo $_SERVER['PHP_SELF']; ?>" method="post">
<input type="submit" value="Next" name="submit">
</form>
</body>
</html>
education.php :
<?php
echo "Successfully Updated.";
?>
You will have to set an action to your form like below because you are not submitting the form, but just redirection to another page without taking the form data.
<form action="education.php" method="post">
<!-- All your input fields here -->
<input type="submit" name="submit" value="Next">
</form>
and your education.php should be look like this:
<?php
//Get all parameters using $_POST
//Make A connection to database
//Choose a database in which you have to save the data
//Create a SQL query
// run query using mysql_query($query);
//Redirect to anywhere with header("Location:page.php");
?>

ECHO page1.php textarea values into page2.php

I have 2 php files in my folder. In page1.php, there's a textarea, user should enter some values in it. In page2.php, it will grab what is in the textarea and work with its program. But I can't find a command that grabs the value in textarea. Can someone help me?
page1.php:
<?
$hello = "hello";
?>
<html>
<input type = "text" name = "user_input">
</input>
</html>
page2.php
<?
ob_start();
include 'page1.php';
ob_end_clean();
echo $hello;
?>
So, is there anyone that can solve this? =/
Use $_GET or $_POST in page2.php
page1.php
<?
$hello = "hello";
?>
<html>
<form method="get" action="page2.php" enctype="multipart/form-data">
<input type = "text" name = "user_input">
<input type="submit">
</form>
</html>
page2.php
<?
$text=$_GET['user_input'];
ob_start();
include 'page1.php';
ob_end_clean();
echo $hello;
echo $text;
?>
You may use either $_GET['user_input'] or $_POST['user_input'].
The difference is, you can see the data in the url (visible to everyone) when using GET method and not in the other method.
Also, always use <input> elements (which you want to pass to another file) inside a <form> and specify action="file.php", to where you want to pass data, and the method, either method="get" or method="post", like;
<form method="get" action="page2.php">
also specify the method to grab data in the target file also, like;
$text=$_GET['user_input']; or $text=$_POST['user_input'];
And in your case, you may use;
Method 1
<?php
$hello = "hello";
?>
<html>
<form method="get" action="page2.php">
<input type="text" name="user_input">
<input type="submit">
</form>
</html>
page2.php
<?php
$text=$_GET['user_input'];
echo $text;
?>
Method 2
<?php
$hello = "hello";
?>
<html>
<form method="post" action="page2.php">
<input type="text" name="user_input">
<input type="submit">
</form>
</html>
page2.php
<?php
$text=$_POST['user_input'];
echo $text;
?>
If you want to share the data over a number of pages, you may do this using PHP Session or saving the data in a cookie.
1. Using Sessions
<?php
session_start();
$_SESSION['data'] = 1; // store session data
echo "Pageviews = ". $_SESSION['data']; //retrieve data
?>
Make sure you add session_start(); on every page you want to handle session
You can read more about php sessions here www.tizag.com/phpT/phpsessions.php/
2. Using Cookie
<?php
setcookie("user", "Alex Porter", time()+3600);
?>
and retreive it using
echo $_COOKIE["user"];
You can read more about php sessions here http://www.w3schools.com/php/php_cookies.asp
hope this helps...:)
basically your page1.php is a page with some form in it with a text area. Now user will have to fill it and submit the form to page2.php. You can't echo it's content like that, because that will be on browser subject to user actions. Use a form and submit the data to page2.php. Like this:
page1.php
<html>
<head>
</head>
<body>
<form action="page2.php" method="post">
<textarea name="t1">
</textarea>
</form>
</body>
</html>
page2.php
<?php
$textAreaContents = isset($_POST['t1'])?$_POST['t1']:'';
echo "You submitted: ".$textAreaContents;
?>
if i were you i should use sessions for this. that is where they were made for..
example:when user clicks on submit.
<?php
if($_SERVER['REQUEST_METHOD'] == 'POST')
{
$_SESSION['post'] = $_POST;
}
that is where every post variable will be put in a session.
and your inputbox will be something like this..
<textarea name="message" type="text" value="" rows="0" cols="0" placeholder="" ><?php if(isset($_SESSION['post'])){echo $_SESSION['post']['message'];} ?></textarea>
?>
note that you now can use every post variable that you used in your form by echo (example)
echo $_SESSION['post']['message']
where message is the name of the inputbox. in this case of the textarea
don't forget that at the end when you don't want to use the session anymore use session_destroy(); otherwise you will keep having it in your form. and don't forget session_start(); above every page where you are planning to use sessions ( it must be at 1st line of your document at all times)

Refresh page after form submitting

I have a little problem. I want to reload my page after submitting a form.
<form method="post" action="">
<textarea cols="30" rows="4" name="update" id="update" maxlength="200" ></textarea>
<br />
<input type="submit" value=" Update " id="update_button" class="update_button"/>
</form>
only use
echo "<meta http-equiv='refresh' content='0'>";
right after insert query before }
example
if(isset($_POST['submit']))
{
SQL QUERY----
echo "<meta http-equiv='refresh' content='0'>";
}
<form method="post" action="<?php echo $_SERVER['PHP_SELF']; ?>"> <!-- notice the updated action -->
<textarea cols="30" rows="4" name="update" id="update" maxlength="200" ></textarea>
<br />
<input name="submit_button" type="submit" value=" Update " id="update_button" class="update_button"/> <!-- notice added name="" -->
</form>
on your full page, you could have this
<?php
// check if the form was submitted
if ($_POST['submit_button']) {
// this means the submit button was clicked, and the form has refreshed the page
// to access the content in text area, you would do this
$a = $_POST['update'];
// now $a contains the data from the textarea, so you can do whatever with it
// this will echo the data on the page
echo $a;
}
else {
// form not submitted, so show the form
?>
<form method="post" action="<?php echo $_SERVER['PHP_SELF']; ?>"> <!-- notice the updated action -->
<textarea cols="30" rows="4" name="update" id="update" maxlength="200" ></textarea>
<br />
<input name="submit_button" type="submit" value=" Update " id="update_button" class="update_button"/> <!-- notice added name="" -->
</form>
<?php
} // end "else" loop
?>
If you want the form to be submitted on the same page then remove the action from the form attributes.
<form method="POST" name="myform">
<!-- Your HTML code Here -->
</form>
However, If you want to reload the page or redirect the page after submitting the form from another file then you call this function in php and it will redirect the page in 0 seconds. Also, You can use the header if you want to, just make sure you don't have any content before using the header
function page_redirect($location)
{
echo '<META HTTP-EQUIV="Refresh" Content="0; URL='.$location.'">';
exit;
}
// I want the page to go to google.
// page_redirect("http://www.google.com")
LOL, I'm just wondering why no one had idea about the PHP header function:
header("Refresh: 0"); // here 0 is in seconds
I use this, so user is not prompt to resubmit data if he refresh the page.
See Refresh a page using PHP for more details
You can maybe use :
<form method="post" action=" " onSubmit="window.location.reload()">
<form method="post" action="">
<table>
<tr><td><input name="Submit" type="submit" value="refresh"></td></tr>
</table>
</form>
<?php
if(isset($_POST['Submit']))
{
header("Location: http://yourpagehere.com");
}
?>
action attribute in <form method="post" action="action="""> should be just action=""
You want a form that self submits? Then you just leave the "action" parameter blank.
like:
<form method="post" action="" />
If you want to process the form with this page, then make sure that you have some mechanism in the form or session data to test whether it was properly submitted and to ensure you're not trying to process the empty form.
You might want another mechanism to decide if the form was filled out and submitted but is invalid. I usually use a hidden input field that matches a session variable to decide whether the user has clicked submit or just loaded the page for the first time. By giving a unique value each time and setting the session data to the same value, you can also avoid duplicate submissions if the user clicks submit twice.
//insert this php code, at the end after your closing html tag.
<?php
//setting connection to database
$con = mysqli_connect("localhost","your-username","your-
passowrd","your-dbname");
if(isset($_POST['submit_button'])){
$txt_area = $_POST['update'];
$Our_query= "INSERT INTO your-table-name (field1name, field2name)
VALUES ('abc','def')"; // values should match data
// type to field names
$insert_query = mysqli_query($con, $Our_query);
if($insert_query){
echo "<script>window.open('form.php','_self') </script>";
// supposing form.php is where you have created this form
}
} //if statement close
?>
Hope this helps.

POST without redirect with PHP

I have a simple form for a mailing list that I found at http://www.notonebit.com/projects/mailing-list/
The problem is when I click submit all I want it to do is display a message under the current form saying "Thanks for subscribing" without any redirect. Instead, it directs me to a completely new page.
<form method="POST" action="mlml/process.php">
<input type="text" name="address" id="email" maxlength="30" size="23">
<input type="submit" value="" id="submit"name="submit" >
</form>
You will need AJAX to post the data to your server. The best solution is to implement the regular posting, so that will at least work. Then, you can hook into that using Javascript. That way, posting will work (with a refresh) when someone doesn't have Javascript.
If found a good article on posting forms with AJAX using JQuery .
In addition, you can choose to post the data to the same url. The JQuery library will add the HTTP_X_REQUESTED_WITH header, of which you can check the value in your server side script. That will allow you to post to the same url but return a different value (entire page, or just a specific response, depending on being an AJAX request or not).
So you can actually get the url from your form and won't need to code it in your Javascript too. That allows you to write a more maintanable script, and may even lead to a generic form handling method that you can reuse for all forms you want to post using Ajax.
Quite simple with jQuery:
<form id="mail_subscribe">
<input type="text" name="address" id="email" maxlength="30" size="23">
<input type="hidden" name="action" value="subscribe" />
<input type="submit" value="" id="submit"name="submit" >
</form>
<p style="display: none;" id="notification">Thank You!</p>
<script>
$('#mail_subscribe').submit(function() {
var post_data = $('#mail_subscribe').serialize();
$.post('mlml/process.php', post_data, function(data) {
$('#notification').show();
});
});
</script>
and in your process.php:
<?php
if(isset($_POST['action'])) {
switch($_POST['action']) {
case 'subscribe' :
$email_address = $_POST['address'];
//do some db stuff...
//if you echo out something, it will be available in the data-argument of the
//ajax-post-callback-function and can be displayed on the html-site
break;
}
}
?>
It redirects to a different page because of your action attribute.
Try:
<form method="POST" action="<?php echo $_SERVER['PHP_SELF'] ?>">
<input type="text" name="address" id="email" maxlength="30" size="23" />
<input type="submit" value="" id="submit" name="submit" />
</form>
<?php if (isset($_POST['submit'])) : ?>
<p>Thank you for subscribing!</p>
<?php endif; ?>
The page will show your "Thank You" message after the user clicks your submit button.
Also, since I don't know the name of the page your code is on, I inserted a superglobal variable that will insert the the filename of the currently executing script, relative to the document root. So, this page will submit to itself.
You have to use AJAX. But that requires JavaScript to be active at the users Brwoser.
In my opinion it's the only way to do without redirect.
to send a form request without redirecting is impossible in php but there is a way you can work around it.
<form method="post" action="http://yoururl.com/recv.php" target="_self">
<input type="text" name="somedata" id="somedata" />
<input type="submit" name="submit" value="Submit!" />
</form>
then for the php page its sending to have it do something but DO NOT echo back a result, instead simply redirect using
header( 'Location: http://yourotherurl.com/formpage' );
if you want it to send back a success message simply do
$success = "true";
header( 'Location: http://yourotherurl.com/formpage?success='.$success);
and on the formpage add
$success = $_GET['success'];
if($success == "true"){ echo 'Your success message'; } else { echo
'Your failure message';
Return and print the contents of another page on the current page.
index.php
<html>
<body>
<p>index.php</p>
<form name="form1" method="post" action="">
Name: <input type="text" name="search">
<input type="submit">
</form>
<?php
if ($_SERVER["REQUEST_METHOD"] == "POST") {
$_POST['search'];
include 'test.php';
}
?>
</body>
</html>
test.php
<?php
echo 'test.php <br/>';
echo 'data posted is: ' . $_POST['search'];
?>
Result:
Just an idea that might work for you assuming you have no control over the page you are posting to:
Create your own "proxy php target" for action and then reply with the message you want. The data that was posted to your php file can then be forwarded with http_post_data (Perform POST request with pre-encoded data). You might need to parse it a bit.
ENGLISH Version
It seems that no one has solved this problem without javascript or ajax
You can also do the following.
Save a php file with the functions and then send them to the index of your page
Example
INDEX.PHP
<div>
<?php include 'tools/edit.php';?>
<form method="post">
<input type="submit" name="disable" value="Disable" />
<input type="submit" name="enable" value="Enable" />
</form>
</div>
Tools.php (It can be any name, note that it is kept in a folder lame tools)
<?php
if(isset($_POST['enable'])) {
echo "Enable";
} else {
}
if(isset($_POST['disable'])) {
echo "Disable";
} else {
}
?>
Use
form onsubmit="takeActions();return false;"
function takeAction(){
var value1 = document.getElementById('name').innerHTML;
// make an AJAX call and send all the values to it
// Once , you are done with AJAX, time to say Thanks :)
document.getElementById('reqDiv').innerHTML = "Thank You for subscribing";
}

Categories