Athirah Hazira Athirah Hazira - 5 months ago 18
PHP Question

Clear forms on successful submission

I have a registration form where the form will:


  1. Clear form on a successful submission

  2. Don't clear form on an error submission (in my case, unmatched passwords)



Here's my code:

<input name="uname" type="text" class="form-control" id="uname" placeholder="Username" value="<?php if (!empty($_POST["uname"])) { echo $_POST["uname"]; } else { echo ''; }; ?>" required>


This code works for the don't clear form on an error submission. Although the submission is successful, the form still keeps the data after the form submission. Since, i'm using this code, obviously the reset button won't work too. Therefore, how do i clear it after successful submission?

Anyway here's the code for form validation:

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

try {

if ($_POST["pwd"] == $_POST["cpwd"]) {//matched passwords

$stmt = $conn->prepare("INSERT INTO tbl_customers(fld_customer_fname,
fld_customer_lname, fld_customer_gender, fld_customer_phone, fld_customer_email, fld_customer_username, fld_customer_password) VALUES(:fname, :lname,
:gender, :phone, :email, :uname, :pwd)");

$stmt->bindParam(':fname', $fname, PDO::PARAM_STR);
$stmt->bindParam(':lname', $lname, PDO::PARAM_STR);
$stmt->bindParam(':gender', $gender, PDO::PARAM_STR);
$stmt->bindParam(':phone', $phone, PDO::PARAM_STR);
$stmt->bindParam(':email', $email, PDO::PARAM_STR);
$stmt->bindParam(':uname', $uname, PDO::PARAM_STR);
$stmt->bindParam(':pwd', $pwd, PDO::PARAM_STR);

$fname = $_POST['fname'];
$lname = $_POST['lname'];
$gender = $_POST['gender'];
$phone = $_POST['phone'];
$email = $_POST['email'];
$uname = $_POST['uname'];
$pwd = $_POST['pwd'];

$stmt->execute();
?>
<br>
<div class="alert alert-success fade in">
<button type="button" class="close" data-dismiss="alert" aria-label="Close">
<span aria-hidden="true">&times;</span>
</button>
<strong>Success!</strong> Account created.
</div>
<?php
}
else{//unmatched passwords
?>
<br>
<div class="alert alert-danger fade in">
<button type="button" class="close" data-dismiss="alert" aria-label="Close">
<span aria-hidden="true">&times;</span>
</button>
<strong>Error!</strong> Passwords do not match.
</div>
<?php
}
}

Answer

I assume you render your form fields after you check if it was success or not. If I am right, set in success also some $success variable to true

$success = true;

when you have success or to false where not. And then in rendering input just do:

<input name="uname" type="text" class="form-control" id="uname" placeholder="Username" value="<?php if (!empty($_POST["uname"]) && !$success) { echo $_POST["uname"]; } ?>" required>

ps: you do not need else { echo ''; }; ;)

Comments