php - 如何阻止表单提交按钮刷新页面?

标签 php validation jquery form-submit

我正在使用 php 自验证表单,我需要阻止提交按钮刷新页面,因为我需要始终停留在索引页面上(我正在使用 ajax 将内容加载到主页上) 。我已经尝试过以下代码片段,但它会覆盖 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); 
  }
?>

最佳答案

要部分提交表单,您需要在简单的按钮/ anchor 单击上调用 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 - 如何阻止表单提交按钮刷新页面?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/20551586/

相关文章:

php - Laravel 如何验证一行中的数据,而不是检查整个表

javascript - 如何解析在另一个文档中声明的 javascript 变量?

javascript - document.lastModified 在 div 中使用 JQuery

javascript - 如何使用 jquery 将正则表达式应用于客户端文件的内容?

PHP/MySQL 卫生问题

php - 将带有 std::accumulate 的 C++ 映射移植到 PHP

javascript - Input Onkeyup 可以通过表单自动完成来避免

ruby-on-rails - Ruby on Rails 在 jsonb(哈希)中验证日期

jquery - jqGrid:重新加载数据

php - 避开 laravel 的公用文件夹,直接在 web 服务器中打开根目录