【问题标题】:How to stop form submit button from refreshing page?如何从刷新页面停止表单提交按钮?
【发布时间】:2013-12-31 08:11:36
【问题描述】:

我正在使用 php 自我验证表单,我需要阻止提交按钮刷新页面,因为我需要始终停留在索引页面上(我正在使用 ajax 将内容加载到主页上) .我已经尝试了以下 sn-p 代码,但它会覆盖 php 验证并显示感谢消息,即使表单为空...我可以只使用 php 停止刷新并在屏幕上打印感谢消息吗?我的网站位于 www.vgtesting.co.nf

              $(function () {
       $('form').on('submit', function (e) {
          $.ajax({
            type: 'post',
             url: 'contact.php',
             data: $('form').serialize(),
                   success: function () {
                 alert('Thank you! your form has been submitted');
                     }
                  });
           e.preventDefault();
          });
                  });

     <?php
  function test_input($data)
  {
     $data = trim($data);
     $data = stripslashes($data);
     $data = htmlspecialchars($data);
     return $data;
  }

// define variables and set to empty values
$firstnameErr = $lastnameErr = $emailErr = $cellphoneErr = $genDerErr = $dognameErr = $BreedErr = $reasonErr = "";
$firstname = $lastname = $email = $cellphone = $genDer = $dogname = $Breed = $reasoNwalk = $reasoNgroom = $reasoNfood  = $reasoNtraining = $freecomments = "";

$formValid = true; // Define a boolean and set to true before validating 

//if conditional statement stops PHP from looking for variable values until the submit button is hit
if ($_SERVER["REQUEST_METHOD"] == "POST")
{
  // check if a first name was provided
   if (empty($_POST["firstname"]))
     {
     $firstnameErr = "A first name is required";
     $formValid = false; // Invalid input - set the flag to false
     }
   else 
     {
     $firstname = test_input($_POST["firstname"]);
     // check if name only contains letters and whitespace
       if (!preg_match("/^[a-zA-Z ]*$/",$firstname))
       {
         $firstnameErr = "Only letters and white space allowed";
         $formValid = false; // Invalid input - set the flag to false
       }
     } 
   //check if a last name was provided
    if (empty($_POST["lastname"]))
     {
    $lastnameErr = "A last name is required";
    $formValid = false; // Invalid input - set the flag to false
   }
   else
     {
     $lastname = test_input($_POST["lastname"]);
     // check if name only contains letters and whitespace
      if (!preg_match("/^[a-zA-Z ]*$/",$lastname))
        {
          $lastnameErr = "Only letters and white space allowed";
          $formValid = false; // Invalid input - set the flag to false
        }
     }
   // check if an email was provided
   if (empty($_POST["email"]))
    {
       $emailErr = "Email is required";
       $formValid = false; // Invalid input - set the flag to false
    }
   else
     {
     $email = test_input($_POST["email"]);
     // check if e-mail address syntax is valid
      if (!preg_match("/([\w\-]+\@[\w\-]+\.[\w\-]+)/",$email))
       {
           $emailErr = "Invalid email format";
           $formValid = false; // Invalid input - set the flag to false 
       }
     } 
   if (empty($_POST["cellphone"]))
    {
       $cellphoneErr = "Please provide a phone number";
       $formValid = false; // Invalid input - set the flag to false
    } 
    else
  {
     $cellphone = test_input($_POST["cellphone"]);
     // Regular Expression to allow only valid phone number formats, including numbers, spaces, dashes, extensions
     if (!preg_match("/^(?:(?:\+?1\s*(?:[.-]\s*)?)?(?:\(\s*([2-9]1[02-9]|[2-9][02-8]1|[2-9][02-8][02-9])\s*\)|([2-9]1[02-9]|[2-9][02-8]1|[2-9][02-8][02-9]))\s*(?:[.-]\s*)?)?([2-9]1[02-9]|[2-9][02-9]1|[2-9][02-9]{2})\s*(?:[.-]\s*)?([0-9]{4})(?:\s*(?:#|x\.?|ext\.?|extension)\s*(\d+))?$/",$cellphone))
       {
         $cellphoneErr = "Invalid format";
           $formValid = false; // Invalid input - set the flag to false
       }
     } 

   if (empty($_POST["dogname"]))
    { 
  $dognameErr = "A doggy name is required";
  $formValid = false; // Invalid input - set the flag to false
  } 
    else
  {
     $dogname = test_input($_POST["dogname"]);
     // check if dogname only contains letters and whitespace
    if (!preg_match("/^[a-zA-Z ]*$/",$dogname))
       {
         $dognameErr = "Only letters and white space allowed";
         $formValid = false; // Invalid input - set the flag to false
       }
     } 

   if (empty($_POST["Breed"]))
    {
      $BreedErr = "A breed name is required";
      $formValid = false; // Invalid input - set the flag to false
    } 
    else
  {
     $Breed = test_input($_POST["Breed"]);
     // check if name only contains letters and whitespace
     if (!preg_match("/^[a-zA-Z ]*$/",$Breed))
       {
         $BreedErr = "Only letters and white space allowed";
         $formValid = false; // Invalid input - set the flag to false
       }
     } 
  if(empty($_POST['genDer'])) 
   {
      $genDerErr= "You forgot to select a Gender!";
      $formValid = false; // Invalid input - set the flag to false
   }
  else
  {
    $genDer=($_POST['genDer']);
    }

  //make sure one of the services requested check-boxes are checked
  $reasoNwalk=test_input($_POST["reasoNwalk"]);
  $reasoNfood=test_input($_POST["reasoNfood"]);
  $reasoNgroom=test_input($_POST["reasoNgroom"]);
  $reasoNtraining=test_input($_POST["reasoNtraining"]);

$require_one_of = array('reasoNwalk','reasoNfood','reasoNgroom', 'reasoNtraining'); //names of posted checkboxes
$one_set=false;
foreach($require_one_of as $key){
   if(isset($_POST[$key])){
      $one_set=true;
      break;
   }
}
if(!$one_set){
   $reasonErr = "You forgot to select a service!"; //error handling
}


   // if comment section is not empty then run test_input function to purge possible malicious code 
  if (empty($_POST["freecomments"]))
     {$freecomments = "";}
   else
     {$freecomments = test_input($_POST["freecomments"]);}
 } 

 // wrap the MySQL logic inside a condition so form is only submitted when validation is met
 if ($formValid)
 { 
   $host="fdb3.biz.nf"; //localhost
   $dbuser="1546259_rsginfo"; //user
   $dbpass="RSGnow12"; //pass
   $dbname="1546259_rsginfo"; //db name

// Create connection
$conn=mysqli_connect($host,$dbuser,$dbpass,$dbname);  

// Check connection
if (mysqli_connect_errno($conn))
    {
    echo "Failed to connect to MySQL: " . mysqli_connect_error();
    }
//create query
$sql= "INSERT INTO customer (fname, lname, email, phone, comments)VALUES ('$firstname', '$lastname', '$email', '$cellphone', '$freecomments')";
$sql2= "INSERT INTO DogInfo (DogName, Breed, Gender, walk, groom, food, training )VALUES ('$dogname', '$Breed','$genDer', '$reasoNwalk', '$reasoNgroom', '$reasoNfood', '$reasoNtraining')";

// execute query
mysqli_query($conn,$sql);
mysqli_query($conn, $sql2);

// close connection
mysqli_close($conn); 
  }
?>

【问题讨论】:

  • PHP 是服务器端的。在请求完成之前,它不会影响客户端。
  • 无论如何,这里的一切看起来都是正确的。您的 PHP 页面不能返回失败。
  • 我不明白,我想我需要退后一步
  • e.preventDefault() 在提交表单时停止页面重新加载(在这种情况下,它会停止“提交”事件的默认操作)。然后发送 ajax,您的 PHP 将返回 200 范围内的响应代码 - see here for more on HTTP status codes。如果返回“成功”代码,JQuery 将运行 success 处理程序,这就是您所描述的情况。您的 PHP 必须返回一个错误代码,然后您的 Javascript 可以更新为使用 error 处理程序并响应它。
  • 我已经包含了我的 php 脚本:当我输入所有字段时,表单会提交给 mysql,当我输入无效答案或为空时,它会在 sql 中创建一个空白行,但无论哪种情况,用户都会得到提示并且会认为他们成功了。

标签: php validation jquery form-submit


【解决方案1】:

对于表单的部分提交,您需要在简单的按钮/锚点单击上调用您的 ajax 方法。无需提交表格。

示例 HTML 部分:

<input type="button" onClick="callAjax();" />

<a href="#" onClick="callAjax();">Call AJAX</a>

Javascript 部分:

function callAjax(){
$.ajax({
     type: 'post',
     url: 'contact.php',
     data: $('form').serialize(),
        success: function (response) {
            document.getElementById('anyDivId').innerHTML = response;
        }
    });
}

【讨论】:

  • 它不起作用...“部分提交”是什么意思?我希望仅在完成 ​​php 验证后才提交表单(无需重新加载页面)。
  • 也一样。部分提交意味着将表单数据发送到服务器并重新加载页面。
猜你喜欢
  • 2019-02-09
  • 2015-08-30
  • 2014-04-20
  • 2013-10-27
  • 1970-01-01
相关资源
最近更新 更多