[php] 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.

This question is related to php html forms submit

The answer is


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>

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.


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>

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.


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>

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"); ?>

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; 
   }
 ?>

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)


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

<form method="post" action="<?=$_SERVER['PHP_SELF'];?>">

Examples related to php

I am receiving warning in Facebook Application using PHP SDK Pass PDO prepared statement to variables Parse error: syntax error, unexpected [ Preg_match backtrack error Removing "http://" from a string How do I hide the PHP explode delimiter from submitted form results? Problems with installation of Google App Engine SDK for php in OS X Laravel 4 with Sentry 2 add user to a group on Registration php & mysql query not echoing in html with tags? How do I show a message in the foreach loop?

Examples related to html

Embed ruby within URL : Middleman Blog Please help me convert this script to a simple image slider Generating a list of pages (not posts) without the index file Why there is this "clear" class before footer? Is it possible to change the content HTML5 alert messages? Getting all files in directory with ajax DevTools failed to load SourceMap: Could not load content for chrome-extension How to set width of mat-table column in angular? How to open a link in new tab using angular? ERROR Error: Uncaught (in promise), Cannot match any routes. URL Segment

Examples related to forms

How do I hide the PHP explode delimiter from submitted form results? React - clearing an input value after form submit How to prevent page from reloading after form submit - JQuery Input type number "only numeric value" validation Redirecting to a page after submitting form in HTML Clearing input in vuejs form Cleanest way to reset forms Reactjs - Form input validation No value accessor for form control TypeScript-'s Angular Framework Error - "There is no directive with exportAs set to ngForm"

Examples related to submit

React - clearing an input value after form submit angular2 submit form by pressing enter without submit button spark submit add multiple jars in classpath jQuery's .on() method combined with the submit event Selenium Webdriver submit() vs click() PHP form - on submit stay on same page Disable submit button ONLY after submit HTML - How to do a Confirmation popup to a Submit button and then send the request? HTML form with multiple "actions" Javascript change color of text and background to input value