PHP form - on submit stay on same page

mewebs picture mewebs · Jun 27, 2013 · Viewed 307.5k times · Source

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.

Answer

Tom Groot picture Tom Groot · Jul 20, 2014

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>