我正在使用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);
}
?>
答案 0 :(得分:2)
对于部分提交表单,您需要在简单的按钮/锚点击上调用您的ajax方法。无需提交表格。
示例HTML部分:
<input type="button" onClick="callAjax();" />
OR
<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;
}
});
}