47

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.

Peter Mortensen
  • 30,738
  • 21
  • 105
  • 131
mewebs
  • 535
  • 2
  • 5
  • 11

11 Answers11

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>
miken32
  • 42,008
  • 16
  • 111
  • 154
Tom Groot
  • 1,160
  • 1
  • 9
  • 26
  • 3
    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??? – Apostolos Jun 16 '17 at 07:59
  • @Apostolos so how would i go about using this example the right way? what would need to be changed? – Lyux Jun 14 '18 at 12:52
  • 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" ... – Apostolos Jun 15 '18 at 10:04
  • 1
    Add `if(isset($message)){...}` around `echo $message;` to make sure"Notice: Undefined variable message" doesn't appear anymore. – Tom Groot Jun 27 '18 at 20:31
  • What about [using `#` instead](https://stackoverflow.com/questions/17333901/php-form-on-submit-stay-on-same-page/41563564#41563564)? Pros and cons? – Peter Mortensen Nov 25 '19 at 19:56
19

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

<form method="post" action="<?=$_SERVER['PHP_SELF'];?>">
Peter Mortensen
  • 30,738
  • 21
  • 105
  • 131
ChaseC
  • 426
  • 2
  • 6
  • 18
  • 1
    It should be noted that this method does not pass the HTML validation check at [W3 Validator](http://validator.w3.org), 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: `
    `
    – Kendall Jul 07 '15 at 15:03
  • There is a code example of this at http://www.html-form-guide.com/php-form/php-form-action-self.html – Mawg says reinstate Monica Feb 12 '16 at 16:17
  • This is of course understood plus it doesn't change anything, since it's the same with action="", which is already mentioned above. – Apostolos Jun 16 '17 at 08:21
  • 2
    Beware, you should use htmlspecialchars($_SERVER['PHP_SELF']). Otherwise it will be subject to xss attacks if someone puts JS in an url. – Mosset Jérémie Jan 25 '19 at 13:17
  • This does exactly the same thing as leaving it empty, but with added XSS security risks. Bad idea. – miken32 May 28 '19 at 16:21
  • 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. – kawerewagaba Jun 16 '19 at 20:26
  • What is the actual resulting HTML? Can you [add an example of it to your answer](https://stackoverflow.com/posts/19458285/edit)? – Peter Mortensen Nov 25 '19 at 19:54
16

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.

HoldOffHunger
  • 18,769
  • 10
  • 104
  • 133
Ashrith Sheshan
  • 654
  • 4
  • 17
  • 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. – Apostolos Jun 16 '17 at 08:05
  • @Apostolos - If the `action` (within the `
    ` tag is set to the current page's URL (or simply `#`) then the same page is reloaded. (Not a new window.)
    – ashleedawg Dec 01 '18 at 12:44
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>
Peter Mortensen
  • 30,738
  • 21
  • 105
  • 131
Surendra Kumar Ahir
  • 1,609
  • 18
  • 19
  • Does this solution suffer from javascript attacks in the URL, like suggested in [this comment](https://stackoverflow.com/questions/17333901/php-form-on-submit-stay-on-same-page#comment95545842_19458285)? Thanks. – user1934286 Jan 25 '23 at 22:53
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>
john abraham
  • 59
  • 1
  • 1
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; 
   }
 ?>
Majbah Habib
  • 8,058
  • 3
  • 36
  • 38
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.

Kamil
  • 13,363
  • 24
  • 88
  • 183
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'];
       }
    ?>
Wria Mohammed
  • 1,433
  • 18
  • 23
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"); ?>
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.

Julian Knight
  • 4,716
  • 2
  • 29
  • 42
  • Correct, but you should include the correct and full code that the reader should include on processForm.php (in the example of the OP). – Frank Conijn - Support Ukraine Jun 06 '22 at 10:12
  • @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. – Julian Knight Jun 06 '22 at 20:25
-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)

Patrick Smit
  • 35
  • 1
  • 7