[php] Clear the form field after successful submission of php form

I am making a simple Form the problem i am facing is when i submit the form values still remains in the field. and I want to clear it after SUCCESSFUL submission. Please help.

here is my code for the form..

<label class="w">Plan :</label>
<select autofocus="" name="plan" required="required">
    <option value="">Select One</option>
    <option value="FREE Account">FREE Account</option>
    <option value="Premium Account Monthly">Premium Account Monthly</option>
    <option value="Premium Account Yearly">Premium Account Yearly</option>
</select>
<br>
<label class="w">First Name :</label><input name="firstname" type="text" placeholder="First Name" required="required" value="<?php echo $_POST['firstname'];?>"><br>
<label class="w">Last Name :</label><input name="lastname" type="text" placeholder="Last Name" required="required" value="<?php echo $_POST['lastname'];?>"><br>
<label class="w">E-mail ID :</label><input name="email" type="email" placeholder="Enter Email" required="required" value="<?php echo $_POST['email'];?>"><br>
<label class="w">Password :</label><input name="password" type="password" placeholder="********" required="required" value="<?php echo $_POST['password'];?>"><br>
<label class="w">Re-Enter Password :</label><input name="confirmpassword" type="password" placeholder="********" required="required" value="<?php echo $_POST['confirmpassword'];?>"><br>
<label class="w">Street Address 1 :</label><input name="strtadd1" type="text" placeholder="street address first" required="required" value="<?php echo $_POST['strtadd1'];?>"><br>
<label class="w">Street Address 2 :</label><input name="strtadd2" type="text" placeholder="street address second"  value="<?php echo $_POST['strtadd2'];?>"><br>
<label class="w">City :</label><input name="city" type="text" placeholder="City" required="required" value="<?php echo $_POST['firstname'];?>"><br>
<label class="w">Country :</label><select autofocus="" id="a1_txtBox1" name="country" required="required" placeholder="select one" value="<?php echo $_POST['country'];?>">

Any help would be appriciated

This question is related to php forms

The answer is


If you want your form's field clear, you must only add a delay in the onClick event like:

<input name="submit" id="MyButton" type="submit" class="btn-lg" value="ClickMe" onClick="setTimeout('clearform()', 2000 );"

onClick="setTimeout('clearform()', 1500 );" . in 1,5 seconds its clear

document.getElementById("name").value = "";  <<<<<<just correct this
document.getElementById("telephone").value = "";    <<<<<correct this

By clearform(), I mean your clearing-fields function.


this code will help you

if($insert){$_POST['name']="";$_POST['content']=""}

You can check this also

_x000D_
_x000D_
<form id="form1" method="post">
<label class="w">Plan :</label>
<select autofocus="" name="plan" required="required">
    <option value="">Select One</option>
    <option value="FREE Account">FREE Account</option>
    <option value="Premium Account Monthly">Premium Account Monthly</option>
    <option value="Premium Account Yearly">Premium Account Yearly</option>
</select>
<br>
<label class="w">First Name :</label><input name="firstname" type="text" placeholder="First Name" required="required" ><br>
<label class="w">Last Name :</label><input name="lastname" type="text" placeholder="Last Name" required="required" ><br>
<label class="w">E-mail ID :</label><input name="email" type="email" placeholder="Enter Email" required="required" ><br>
<label class="w">Password :</label><input name="password" type="password" placeholder="********" required="required"><br>
<label class="w">Re-Enter Password :</label><input name="confirmpassword" type="password" placeholder="********" required="required"><br>
<label class="w">Street Address 1 :</label><input name="strtadd1" type="text" placeholder="street address first" required="required"><br>
<label class="w">Street Address 2 :</label><input name="strtadd2" type="text" placeholder="street address second" ><br>
<label class="w">City :</label>
<input name="city" type="text" placeholder="City" required="required"><br>
<label class="w">Country :</label>
<select autofocus id="a1_txtBox1" name="country" required="required" placeholder="select one">
<option>Select One</option>
<option>UK</option>
<option>US</option>
</select>
<br>
<br>
<input type="reset" value="Submit" />

</form>
_x000D_
_x000D_
_x000D_


I was just trying to fix same error, I finally fixed it, so I will copy to you part of the code, maybe it helps you.

<input type="text" name="usu" id="usu" value="<?php echo $usu;?>" ></input>
<input type="text" name="pass" id="pass" value="<?php echo $varpass;?>"></input>  

those are the inputs I wanted to clean after pressing my button.

And here php code:

$query= "INSERT INTO usuarios (tipo, usuario, password) VALUES ('".$vartipo."', '".$usu."', '".$varpass."')";


        if (!mysqli_query($conexion,$query)){

            die('Error: ' . mysqli_error($conexion));
        }

        else{


            $usu = '';  
            $varpass= '';   

            $result = '<div class="result_ok">El usuario se ha registrado con éxito! <div>';        


        }

$usu = '';
$varpass= '';

those are the lines that cleans the inputs :D


I have a simple form to submit testimonials, I also was having trouble clearing the form, what I did was after the query is submitted successfully I and before redirecting to another page I cleared the imputs $name =''; ect. The page submitted and redirected with no errors.


You can use .reset() on your form.

$(".myform")[0].reset();

I was facing this similiar problem and did not want to use header() to redirect to another page.

Solution:

Use $_POST = array(); to reset the $_POST array at the top of the form, along with the code used to process the form.

The error or success messages can be conditionally added after the form. Hope this helps :)


Here is the solution for when the for is submitted with the successful message all form fields to get cleared. for that set the values equals to false check the code below

<?php
$result_success = '';
$result_error = '';
$full_Name_error = $email_error = $msg_error = '';
$full_Name = $email = $msg = $phoneNumber = '';
$full_Name_test = $email_test = $msg_test = '';

//when the form is submitted POST Method and must be clicked on submit button

if ($_SERVER['REQUEST_METHOD'] == "POST" && isset($_POST['form-submit'])) {
    $full_Name = $_POST['fullName'];
    $email = $_POST['email'];
    $phoneNumber = $_POST['phoneNumber'];
    $msg = $_POST['message'];
    // Form Validation for fullname
    if (empty($full_Name)) {
        $full_Name_error = "Name is required";
    } else {
        $full_Name_test = test_input($full_Name);
        if (!preg_match("/^[a-z A-Z]*$/", $full_Name_test)) {
            $full_Name_error = "Only letters and white spaces are allowed";
        }
    }
    //Form Validation for email
    if (empty($email)) {
        $email_error = "Email is required";
    } else {
        $email_test = test_input($email);
        if (!filter_var($email_test, FILTER_VALIDATE_EMAIL)) {
            $email_error = "Invalid Email format";
        }
    }
    //Form Validation for message
    if (empty($msg)) {
        $msg_error = "Say atleast Hello!";
    } else {
        $msg_test = test_input($msg);
    }
    if ($full_Name_error == '' and $email_error == '' and $msg_error == '') {
        // Here starts PHP Mailer 
        date_default_timezone_set('Etc/UTC');
        // Edit this path if PHPMailer is in a different location.
        require './PHPMailer/PHPMailerAutoload.php';
        $mail = new PHPMailer;
        $mail->isSMTP();
        /*Server Configuration*/
        $mail->Host = 'smtp.gmail.com'; // Which SMTP server to use.
        $mail->Port = 587; // Which port to use, 587 is the default port for TLS security.
        $mail->SMTPSecure = 'tls'; // Which security method to use. TLS is most secure.
        $mail->SMTPAuth = true; // Whether you need to login. This is almost always required.
        $mail->Username = ""; // Your Gmail address.
        $mail->Password = ""; // Your Gmail login password or App Specific Password.
        /*Message Configuration*/
        $mail->setFrom($email, $full_Name); // Set the sender of the message.
        $mail->addAddress(''); // Set the recipient of the message.
        $mail->Subject = 'Contact form submission from your Website'; // The subject of the message
        /*Message Content - Choose simple text or HTML email*/
        $mail->isHTML(true);
        // Choose to send either a simple text email...
        $mail->Body = 'Name: ' . $full_Name . '<br>' . 'PhoneNumber:  ' . $phoneNumber . '<br>' . 'Email:  ' . $email . '<br><br>' . 'Message:  ' . '<h4>' . $msg . '</h4>'; // Set a plain text body.
        // ... or send an email with HTML.
        //$mail->msgHTML(file_get_contents('contents.html'));
        // Optional when using HTML: Set an alternative plain text message for email clients who prefer that.
        //$mail->AltBody = 'This is a plain-text message body'; 
        // Optional: attach a file
        //$mail->addAttachment('images/phpmailer_mini.png');
        if ($mail->send()) {
            $result_success = "Your message was sent successfully!  " . 
            //Here is the solution for when the for is submitted with the successful message all form fields to get cleared.
            $full_Name;
            $full_Name = false;
            $email = false;
            $phoneNumber = false;
            $msg = false;
        } else {
            $result_error = "Something went wrong. Check your Network connection and Please try again.";
        }
    }
}
function test_input($data)
{
    $data = trim($data);
    $data = stripslashes($data);
    $data = htmlspecialchars($data);
    return $data;
}

After submitting the post you can redirect using inline javascript like below:

echo '<script language="javascript">window.location.href=""</script>';              

I use this code all the time to clear form data and reload the current form. The empty href reloads the current page in a reset mode.


// This file is PHP.
<html>    
<?php
    if ($_POST['submit']) {
        $firstname = $_POST['firstname'];
        $lastname = $_POST['lastname'];
        $email = $_POST['email'];
        $password = $_POST['password'];
        $confirmpassword = $_POST['confirmpassword'];
        $strtadd1 = $_POST['strtadd1'];
        $strtadd2 = $_POST['strtadd2'];
        $city = $_POST['city'];
        $country = $_POST['country'];
        $success = '';


        // Upon Success.
        if ($firstname != '' && $lastname != '' && $email != '' && $password != '' && $confirmpassword != '' && $strtadd1 != '' && $strtadd2 != '' && $city != '' && $country != '') {
            // Change $success variable from an empty string.
            $success = 'success';

            // Insert whatever you want to do upon success.

        } else {
            // Upon Failure.
            echo '<p class="error">Fill in all fields.</p>';

            // Set $success variable to an empty string.
            $success = '';
        }
    }
   ?>
<form method="POST" action="#">
    <label class="w">Plan :</label>
    <select autofocus="" name="plan" required="required">
        <option value="">Select One</option>
        <option value="FREE Account">FREE Account</option>
        <option value="Premium Account Monthly">Premium Account Monthly</option>
        <option value="Premium Account Yearly">Premium Account Yearly</option>
    </select>
    <br>
    <label class="w">First Name :</label><input name="firstname" type="text" placeholder="First Name" required="required" value="<?php if (isset($firstname) && $success == '') {echo $firstname;} ?>"><br>
    <label class="w">Last Name :</label><input name="lastname" type="text" placeholder="Last Name" required="required" value="<?php if (isset($lastname) && $success == '') {echo $lastname;} ?>"><br>
    <label class="w">E-mail ID :</label><input name="email" type="email"  placeholder="Enter Email" required="required" value="<?php if (isset($email) && $success == '') {echo $email;} ?>"><br>
    <label class="w">Password :</label><input name="password" type="password" placeholder="********" required="required" value="<?php if (isset($password) && $success == '') {echo $password;} ?>"><br>
    <label class="w">Re-Enter Password :</label><input name="confirmpassword" type="password" placeholder="********" required="required" value="<?php if (isset($confirmpassword) && $success == '') {echo $confirmpassword;} ?>"><br>
    <label class="w">Street Address 1 :</label><input name="strtadd1" type="text" placeholder="street address first" required="required" value="<?php if (isset($strtadd1) && $success == '') {echo $strtadd1;} ?>"><br>
    <label class="w">Street Address 2 :</label><input name="strtadd2" type="text" placeholder="street address second"  value="<?php if (isset($strtadd2) && $success == '') {echo $strtadd2;} ?>"><br>
    <label class="w">City :</label><input name="city" type="text" placeholder="City" required="required" value="<?php if (isset($city) && $success == '') {echo $city;} ?>"><br>
    <label class="w">Country :</label><select autofocus="" id="a1_txtBox1" name="country" required="required" placeholder="select one" value="<?php if (isset($country) && $success == '') {echo $country;} ?>">
    <input type="submit" name="submit">
</form>
</html>

Use value="<?php if (isset($firstname) && $success == '') {echo $firstname;} ?>"
You'll then have to create the $success variable--as I did in my example.


Put the onClick function in the button submit:

<input type="text" id="firstname">
<input type="text" id="lastname">
<input type="submit" value="Submit" onClick="clearform();" />

In the <head>, define the function clearform(), and set the textbox value to "":

function clearform()
{
    document.getElementById("firstname").value=""; //don't forget to set the textbox id
    document.getElementById("lastname").value="";
}

This way the textbox will be cleared when you click the submit button.


The POST data which holds the submitted form data is being echoed in the form, eg:

<input name="firstname" type="text" placeholder="First Name" required="required" 
value="<?php echo $_POST['firstname'];?>"  

Either clear the POST data once you have done with the form - ie all inputs were ok and you have actioned whatever your result from a form is.
Or, once you have determined the form is ok and have actioned whatever you action from the form, redirect the user to a new page to say "all done, thanks" etc.

header('Location: thanks.php');
exit();

This stops the POST data being present, it's know as "Post/Redirect/Get":
http://en.wikipedia.org/wiki/Post/Redirect/Get

The Post/Redirect/Get (PRG) method and using another page also ensures that if users click browser refresh, or back button having navigated somewhere else, your form is not submitted again.
This means if your form inserts into a database, or emails someone (etc), without the PRG method the values will (likely) be inserted/emailed every time they click refresh or revisit the page using their history/back button.