php php表单提交成功后清除表单域

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/20510243/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-25 03:15:12  来源:igfitidea点击:

Clear the form field after successful submission of php form

phpforms

提问by user3077217

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

任何帮助都会被应用

回答by Havenard

They remain in the fields because you are explicitly telling PHP to fill the form with the submitted data.

它们保留在字段中是因为您明确告诉 PHP 使用提交的数据填写表单。

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

Just remove this, or if you want a condition to not do so make a ifstatement to that echoor just cleanup the $_POSTfields.

只需删除它,或者如果您希望条件不这样做,请对此进行if声明echo或只是清理$_POST字段。

$_POST = array(); // lets pretend nothing was posted

Or, if successful, redirect the user to another page:

或者,如果成功,将用户重定向到另一个页面:

header("Location: success.html");
exit; // Location header is set, pointless to send HTML, stop the script

Which by the way is the prefered method. If you keep the user in a page that was reached through a POSTmethod, if he refreshes the page the form will be submitted again.

顺便说一下,这是首选方法。如果您将用户保留在通过POST方法访问的页面中,如果他刷新页面,表单将再次提交。

回答by Jeribo

You can use .reset()on your form.

您可以.reset()在表单上使用。

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

回答by James

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

保存提交的表单数据的 POST 数据在表单中被回显,例如:

<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.

完成表单后清除 POST 数据 - 即所有输入都正常,并且您已经对表单的结果进行了操作。
或者,一旦您确定表单没有问题,并且已经执行了您从表单中执行的任何操作,将用户重定向到一个新页面以说“全部完成,谢谢”等。

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

这会停止存在 POST 数据,它被称为“发布/重定向/获取”: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.

Post/Redirect/Get (PRG) 方法和使用另一个页面还确保如果用户单击浏览器刷新或导航到其他地方的后退按钮,您的表单不会再次提交。
这意味着如果您的表单插入数据库,或通过电子邮件向某人(等)发送电子邮件,而没有 PRG 方法,则每次他们单击刷新或使用历史/返回按钮重新访问页面时,这些值(可能)都会被插入/通过电子邮件发送。

回答by spartan

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

我遇到了这个类似的问题,不想使用 header() 重定向到另一个页面。

Solution:

解决方案:

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

使用$_POST = array();于复位$_POST阵列在表单的顶部,沿与所使用的代码来处理的形式。

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

错误或成功消息可以有条件地添加到表单之后。希望这可以帮助 :)

回答by Haditahh

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:

这里是 php 代码:

$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= '';

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

those are the lines that cleans the inputs :D

这些是清理输入的行:D

回答by Kirankumar Gonti

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

这是当 for 与成功消息一起提交时所有表单字段被清除的解决方案。对于该设置值等于 false 检查下面的代码

<?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;
}

回答by Dash LaLonde

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.

我有一个简单的表单来提交推荐,我也无法清除表单,我所做的是在成功提交查询之后,在重定向到另一个页面之前,我清除了输入 $name =''; 等。页面提交和重定向没有错误。

回答by GlintWeb

this code will help you

此代码将帮助您

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

回答by daniel

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

如果您想清除表单的字段,则只需在 onClick 事件中添加延迟,例如:

<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.

通过clearform(),我的意思是你的清场功能。

回答by Will Bargund Moore

// 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.

使用value="<?php if (isset($firstname) && $success == '') {echo $firstname;} ?>"
然后您必须创建 $success 变量——就像我在我的示例中所做的那样。