I have one form and fields are Name, Email, Message.I am inserting data in the database with the help of ajax and I am using Jquery validator for validation. When I clicked on submit button without filled the fields then I am getting the validation error but the form is also submitting. First, It should check the data in the field proper or not. If data is proper then the form will submit otherwise it will display the validation error. Would you help me in this?
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();