【问题标题】:Clear the form field after successful submission of php formphp表单提交成功后清除表单域
【发布时间】:2013-12-11 03:59:27
【问题描述】:

我正在制作一个简单的表单,我面临的问题是当我提交表单值时仍保留在字段中。我想在成功提交后清除它。请帮忙。

这是我的表单代码..

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

如有任何帮助,将不胜感激

【问题讨论】:

    标签: php forms


    【解决方案1】:

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

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

    只需删除它,或者如果您希望条件不这样做,请对该 echo 进行 if 声明,或者只清理 $_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 方法到达的页面中,如果他刷新页面,表单将再次提交。

    【讨论】:

    • 删除值渲染并不是一个好主意,以防提交不通过。
    • 好吧,如果这是一个好主意,它只取决于他如何编码他的网站。
    • @Havenard:当我删除值=""。在这种情况下,当我提交表单时,我的表单字段为空。但是如果有任何验证,如“电子邮件已经存在”,如果此验证有效,那么我必须再次填写表单,而我不想要。
    • 刷新答案,我已经给出了很多其他的解决方案。
    【解决方案2】:

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

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

    【讨论】:

    • OP 没有使用 JavaScript。这个答案与问题不一致。
    • 如果你使用的是 PHP,你可以这样称呼它: echo "";
    【解决方案3】:

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

    解决方案:

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

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

    【讨论】:

      【解决方案4】:

      这里是当提交成功消息时所有表单字段被清除的解决方案。对于该设置值等于 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;
      }
      

      【讨论】:

      • 最佳解决方案。谢谢。将所有这些字段声明为 false $full_Name = false;
      【解决方案5】:

      保存提交的表单数据的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

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

      【讨论】:

      • 我不想发送任何其他我想在同一页面上显示感谢信息的页面
      • NP - 在这种情况下,在显示表单之前,请使用 $_POST = array(); 清除 $_POST 数组
      • 我怎么做这个??请告诉我
      【解决方案6】:

      在按钮提交中加入onClick函数:

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

      &lt;head&gt;中,定义函数clearform(),设置文本框值为""

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

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

      【讨论】:

      • 在这种情况下,如果验证有效,那么表单也会很清晰。我想如果任何验证工作表不应该是明确的。当且仅当输入的数据正确并存储在数据库中时,表格才会清晰。
      【解决方案7】:

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

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

      这些是清理输入的行:D

      【讨论】:

        【解决方案8】:

        这段代码会帮助你

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

        【讨论】:

          【解决方案9】:

          如果您希望表单的字段清晰,您只能在 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(),我的意思是你的清除字段功能。

          【讨论】:

          • 请不要使用javascript
          【解决方案10】:
          // 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>
          

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

          【讨论】:

            【解决方案11】:

            你也可以检查一下

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

            【讨论】:

            • 感谢您提供此代码 sn-p,它可能会提供一些有限的即时帮助。 proper explanation 将通过展示为什么这是解决问题的好方法,并使其对有其他类似问题的未来读者更有用,从而大大提高其长期价值。请edit您的回答添加一些解释,包括您所做的假设。
            【解决方案12】:

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

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

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

            【讨论】:

              【解决方案13】:

              您也可以使用 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 命令的 Insert a record in the table 之后使用。它会重置在字段中输入的值。

              【讨论】:

                【解决方案14】:

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

                【讨论】:

                  猜你喜欢
                  • 1970-01-01
                  • 1970-01-01
                  • 1970-01-01
                  • 2019-06-07
                  • 1970-01-01
                  • 1970-01-01
                  • 1970-01-01
                  • 1970-01-01
                  • 1970-01-01
                  相关资源
                  最近更新 更多