Frank
Frank

Reputation: 115

How to show form errors on the same page and keep the data the user entered?

I have a form that has action="file.php" , That PHP file has the cheeks and outputs , I want these outputs to be on the same form page.

The form exists in an html file :

 <form class="" method="post" action="file.php">
    <!-- Some Form Fields -->
</form>

The file.php contains some checks and outputs like:

if ($_SERVER["REQUEST_METHOD"] == "POST") {
    $name = $_POST['name'];
    if ( empty($name){
        echo "Name can't be empty.";
    }
}

How to show these outputs on the same page next to the form?

Upvotes: 0

Views: 53

Answers (3)

Andrew
Andrew

Reputation: 20091

If you are posting to the same page, you can echo errors on the same page & retain the posted data no problem with something like this.

in php

   $errors = []
   if (empty($name){
        $errors['name'] = "Name can't be empty.";
    }

... and on the form

<php if (isset($errors['name'])) echo $errors['name']; ?>

<input name='name' value="<?php if (isset($_POST['name'])) echo $_POST['name']; ?>"></input> 

If you are posting to a different url, then you will have to redirect back to the form page or include the form page, and pass the $errors and the $_POST data.

Upvotes: 1

MNN
MNN

Reputation: 302

If you're trying to have that validation in the same form file, let's call it 'form.html', first rename it to 'form.php'. Then add the <?php ?> tags above all the html code, and write your code there.

For that to work, you need to have to left empty the action attribute in form

   <?php
    if ($_SERVER["REQUEST_METHOD"] == "POST") {
        $name = $_POST['name'];
        if ( empty($name){
            echo "Name can't be empty.";
        }
    }
    ?>
    <!-- Some HTML Code-->
    <form class="" method="post" action="">
        <!-- Some Form Fields -->
    </form>

I hope this answer your question about having the code in the same page, but if what you're trying to do is check if field is empty, i recommend you use the 'required' attribute in the html form's input.

Upvotes: 0

Tobia
Tobia

Reputation: 9524

Do everything in the same file.php:

<form class="" method="post" action="file.php">
    <!-- Some Form Fields -->
</form>
if ($_SERVER["REQUEST_METHOD"] == "POST") {
    $name = $_POST['name'];
    if ( empty($name){
        echo "Name can't be empty.";
    }
}

Upvotes: 0

Related Questions