Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

PHP: Refresh page on invalid form submit

Tags:

html

forms

php

How can I refresh a page with a form on submission pending the outcome of the submitted data and display a result.

e.g I have a page with a form:

<form action="" method="post">
   <input type="name" value="" name="name" placeholder="Your Name" />
   <input type="button" name="submit" value="submit form "/>
</form>

The engine that handles the form is external, but required in the page:

require_once 'form_engine.php';

form_engine.php checks the input,

$success = "true";
$errorMessage = " ";
$name = $_POST['name'];

if ( $name == '') {
      $errorMessage = 'Please enter your name';
      $success = false;
}
else (if $success = true) {
   // do something with the data

}

The form page contains the result:

<form action="" method="post">
   <input type="name" value="" name="name" placeholder="Your Name" />
   <input type="button" name="submit" value="submit form "/>
</form>
<p><?php echo $errorMessage; ?></p>

Will the error message get displayed after the form is submitted incorrectly? Or do I have to use a session to store it?

like image 894
user3143218 Avatar asked Dec 25 '22 09:12

user3143218


2 Answers

You need something like this:

if (!isset($_POST['name']))

instead of

if ( $name == 'name')

UPDATE

Try this, it should give you the idea:

<?php

    $errorMessage = false;

    if (isset($_POST['submit'])) {

        if (!isset($_POST['name']) || $_POST['name']=='') {
            $errorMessage = 'Please enter your name';
        }
        else {
           // do something with the data
           echo "Success!!";
        }
    }
?>

<form method="post">
   <input type="name" value="" name="name" placeholder="Your Name" />
   <input type="submit" name="submit" />
</form>
<p><?php if ($errorMessage) echo $errorMessage; ?></p>

Note: leaving out the action attribute will just submit the form to the current page

Note 2: The PHP here could very well be stored in another page. Using require() is the same as putting the code directly into the page.

like image 89
Mark Miller Avatar answered Dec 30 '22 16:12

Mark Miller


You can use redirect on php side:

header('Location: www.mysite.com/index.php');
like image 44
SergeevDMS Avatar answered Dec 30 '22 15:12

SergeevDMS