PHP form - on submit stay on same page
Asked Answered
J

11

48

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.

Jori answered 27/6, 2013 at 3:7 Comment(6)
ajax or post to the same page. I prefer to post to the same page.Dunite
header('contact.html?result=success');Almost
phptutorialforbeginners.com/2013/01/…Dongdonga
Similar question (with a couple of tweaks) to the below: [php, form using the same page after submittion][1] [1]: #15130993Cheriecherilyn
where do i put the header, in the contact.html or the processForm.php?Jori
html-form-guide.com/php-form/php-form-action-self.htmlIselaisenberg
D
57

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>
Damnation answered 20/7, 2014 at 21:15 Comment(5)
Have you checked your code? 1) On first run, before submission, you get "Undefined variable message" (of course!) 2) Then at each submission e new form is loaded displaying the message and they are all built up in browser's history! Why don't you people check your codes before posting them???Ferocious
@Ferocious so how would i go about using this example the right way? what would need to be changed?Financier
I can't remember. I don't work with PHP since about a year ago plus I don't have an Apachi server available at the moment for testing. Sorry. But from what I remember, I managed to stay in the same page (i.e. the PHP file) using "include" ...Ferocious
Add if(isset($message)){...} around echo $message; to make sure"Notice: Undefined variable message" doesn't appear anymore.Damnation
What about using # instead? Pros and cons?Peplos
L
19

The best way to stay on the same page is to post to the same page:

<form method="post" action="<?=$_SERVER['PHP_SELF'];?>">
Livelong answered 18/10, 2013 at 20:13 Comment(7)
It should be noted that this method does not pass the HTML validation check at W3 Validator, as it says "Bad value for attribute action on element form: Must be non-empty." Although it definitely works, the HTML prints like this, which causes the error: <form name="frmContactUs" action="" method="post">Joinder
There is a code example of this at html-form-guide.com/php-form/php-form-action-self.htmlIselaisenberg
This is of course understood plus it doesn't change anything, since it's the same with action="", which is already mentioned above.Ferocious
Beware, you should use htmlspecialchars($_SERVER['PHP_SELF']). Otherwise it will be subject to xss attacks if someone puts JS in an url.Vociferate
This does exactly the same thing as leaving it empty, but with added XSS security risks. Bad idea.Commutative
It should be noted that this doesn't work for paths that have url parameters such as id. Leaving the action value empty works fine tho.Osteopathy
What is the actual resulting HTML? Can you add an example of it to your answer?Peplos
A
17

There are two ways of doing it:

  1. 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
    }
    
  2. Using AJAX Form Submission which is a little more difficult for a beginner than method #1.

Aristotelian answered 27/6, 2013 at 3:15 Comment(2)
Yes, this works, at least partly. You don't stay on the same oage -- since the result is shown in a new page -- but it is much better, since you have to get back to the first page, thus avoiding bulding up copies of the same PHP in browser's history.Ferocious
@Ferocious - If the action (within the <form> tag is set to the current page's URL (or simply #) then the same page is reloaded. (Not a new window.)Longhand
P
9

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>
Production answered 10/1, 2017 at 7:39 Comment(1)
Does this solution suffer from javascript attacks in the URL, like suggested in this comment? Thanks.Drivein
B
5

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>
Baseman answered 23/2, 2018 at 3:32 Comment(0)
T
4

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; 
   }
 ?>
Testament answered 1/5, 2019 at 17:10 Comment(0)
P
2

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.

Puree answered 27/6, 2013 at 3:19 Comment(0)
F
2

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'];
       }
    ?>
Forayer answered 29/11, 2021 at 18:23 Comment(0)
O
0

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"); ?>
Ogdoad answered 25/10, 2017 at 14:8 Comment(2)
This will refresh the page.Braynard
In no way shape or form does that do what the OP is asking: that after submitting the form, the user stays on the page with the form.Ultravirus
G
0

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.

Gnarled answered 25/3, 2022 at 17:39 Comment(2)
Correct, but you should include the correct and full code that the reader should include on processForm.php (in the example of the OP).Ultravirus
@FrankConijn-SupportUkraine, I would love to but I haven't used PHP for over a decade, maybe >2 decades now! I found this when looking for something similar and I noticed that the other answers were rather dated and advising complex answers that are no longer required. If you know how to return a 204 status using PHP, please do feel free to update the answer.Gnarled
F
-2

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)

Folksy answered 30/1, 2019 at 19:35 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.