成功提交php表单后清除表单字段

时间:2013-12-11 03:59:28

标签: php forms

我正在制作一个简单的表格,我面临的问题是,当我提交表格时,价值仍然存在于该字段中。我想在SUCCESSFUL提交后清除它。请帮忙。

这是我的表格代码..

<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'];?>">

任何帮助都是适当的

14 个答案:

答案 0 :(得分:8)

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

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

只需删除此内容,或者如果您希望条件不这样做,请向if发出echo语句,或者只清理$_POST字段。

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

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

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

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

答案 1 :(得分:6)

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

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

答案 2 :(得分:2)

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

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

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

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

这会停止POST数据的存在,它被称为“Post / Redirect / Get”:
http://en.wikipedia.org/wiki/Post/Redirect/Get

发布/重定向/获取(PRG)方法以及使用其他页面还可确保如果用户单击浏览器刷新,或者在其他位置导航后退按钮,则不会再次提交表单。
这意味着如果您的表单插入数据库,或通过电子邮件发送给某人(等),而不使用PRG方法,每次点击刷新或使用历史记录/后退按钮重新访问页面时,都会(可能)插入/发送电子邮件。

答案 3 :(得分:2)

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

解决方案:

使用$_POST = array();重置表单顶部的$_POST数组,以及用于处理表单的代码。

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

答案 4 :(得分:1)

onClick功能放在按钮提交中:

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

<head>中,定义函数clearform(),并将文本框值设置为""

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

这样,当您单击“提交”按钮时,文本框将被清除。

答案 5 :(得分:1)

我只是想修复同样的错误,我终于修复了它,所以我会将部分代码复制给你,也许它可以帮助你。

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

按下我的按钮后,这些是我想要清理的输入。

这里是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 =&#39;&#39;;
$ varpass =&#39;&#39;;

这些是清理输入的行:D

答案 6 :(得分:0)

此代码可以帮助您

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

答案 7 :(得分:0)

如果您希望表单字段清晰,则必须在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

clearform(),我的意思是您的清算字段功能。

答案 8 :(得分:0)

value="<?php if (isset($firstname) && $success == '') {echo $firstname;} ?>"

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

答案 9 :(得分:0)

这是解决方案,用于在提交带有成功消息的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;
}

答案 10 :(得分:0)

我有一个简单的表单来提交推荐书,我在清理表单时也遇到了麻烦,在成功提交查询之后,在重定向到另一个页面之前,我清除了输入变量$ name ='';等等该页面已提交并重定向,没有错误。

答案 11 :(得分:0)

您也可以检查

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

答案 12 :(得分:0)

提交帖子后,您可以使用内嵌 javascript 重定向,如下所示:

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

我一直使用这段代码来清除表单数据并重新加载当前表单。空的 href 以重置模式重新加载当前页面。

答案 13 :(得分:0)

您也可以使用 unset 函数来执行此操作,例如下面是我验证电子邮件存在的代码。

    if($mail->check($email)){
        $status = 'succ';
        $statusMsg = 'Given email &lt;'.$email.'&gt; exists!';
        unset($_REQUEST["name"]);
        unset($_REQUEST["email"]);
        unset($_REQUEST["comment"]);

    }elseif(verifyEmail::validate($email)){
        $status = 'err';
        $statusMsg = 'Given email &lt;'.$email.'&gt; is valid, but does not exist!';
    }else{
        $status = 'err';
        $statusMsg = 'Given email &lt;'.$email.'&gt; is not valid, not exist!';
    }
}else{
    $status = 'err';
    $statusMsg = 'Enter the email address that is to be verified';
}

这个可以在插入一条记录到表中的mysql命令之后使用,就可以了。它会重置在字段中输入的值。