我有一个表单,字段是Name,Email,Message。我在ajax的帮助下在数据库中插入数据,我使用Jquery验证器进行验证。当我点击提交按钮而没有填写字段然后我收到验证错误但表单也提交。首先,它应该检查字段中的数据是否正确。如果数据正确,则表单将提交,否则将显示验证错误。你能帮帮我吗?
HTML
<form name="contact_form" id="form_sub" method="post">
<input type="text" name="name" id="name"><br>
<input type="email" name="email" id="email"><br>
<textarea name="message" id="message"></textarea><br />
<input name="submit" type="submit" value="submit">
<span class="success">Message was Sent</span>
</form>
<script src="http://code.jquery.com/jquery-1.9.1.js"></script>
<script src="js/jquery.validate.min.js"></script>
<script type="text/javascript">
// When the browser is ready...
$(function() {
// Setup form validation on the #register-form element
$("form[name='contact_form']").validate({
// Specify the validation rules
rules: {
name:{ required: true,
minlength:3,
maxlength:30
},
email: {
required: true,
email: true
},
message:{
required: true,
minlength:10,
maxlength:500
}
},
// Specify the validation error messages
messages: {
name:
{
required:"Please enter your name",
minlength:"Please enter min 3 character"
},
email: "Please enter a valid email address",
message: {
required:"Please enter your message",
minlength:"Please enter min 10 character",
maxlength:"Not more then 500 character"
}
},
submitHandler: function(form) {
form.submit();
}
});
});
$(function () {
$('#form_sub').submit('click', function (event) {
event.preventDefault();// using this page stop being refreshing
$.ajax({
type: 'POST',
url: 'demo2.php',
data: $('#form_sub').serialize(),
success: function () {
$('.success').fadeIn(200).show();
}
});
});
});
</script>
PHP
$name=$_POST['name'];
$email=$_POST['email'];
$user_message=$_POST['message'];
$servername = "localhost";
$username = "root";
$password = "";
$dbname = "demo";
// Create connection
$conn = new mysqli($servername, $username, $password, $dbname);
// Check connection
if ($conn->connect_error) {
die("Connection failed: " . $conn->connect_error);
}
$sql = "INSERT INTO contactus(name, email, message) VALUES ('$name', '$email', '$user_message')";
if ($conn->query($sql) === TRUE) {
} else {
echo "Error: " . $sql . "<br>" . $conn->error;
}
$conn->close();
答案 0 :(得分:0)
您需要将提交功能内容移动到提交处理程序中:
submitHandler: function ( form ) {
$.ajax( {
type: 'POST',
url: 'demo2.php',
data: $( '#form_sub' ).serialize(),
success: function () {
$( '.success' ).fadeIn( 200 ).show();
}
});
}