Here is my code that is not working with the jquery validator and ajax. This code does validate and the serialize()
function seems to work because in the browser I see the data but it is not reaching my success because it just refreshed the page and the data does not go into mysql. Been reading all sorts of threads and nothing is working.
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.3/jquery.min.js"></script>
<script src="http://ajax.aspnetcdn.com/ajax/jquery.validate/1.11.1/jquery.validate.min.js"></script>
<script src="http://malsup.github.com/jquery.form.js"></script>
<script>
//validate contact form
$(document).ready(function() {
$("#form_contact").validate({
rules: {
firstname: {
required: true,
minlength: 2
},
lastname: {
required: true,
minlength: 2
},
email: {
required: true,
email: true
},
message: {
required: true,
minlength: 2
}
},
messages: {
firstname: {
required: "Please enter your first name"
},
lastname: {
required: "Please enter your last name"
},
email: {
required: "Please enter your email address."
},
message: {
required: "Please enter a message."
}
},
submitHandler: function(form) {
var d = $("#form_contact").serialize();
$.ajax({
url: '/assets/php/index.php',
type: 'POST',
//dataType: 'text',
data: d,
success: function(data) {
//$('#form_contact').hide();
$("#thanks").text("Thank you for your message. I will get back to you shortly.");
$("#form_contact")[0].reset(); // To reset form fields on success.
return false;
}
}):
}
return false;
});
});
</script>
I think you should define error handler in $.ajax
call. And I think it refreshes cause return false is only in success handler but it is not called if there is some error. So define the error handler with console.log(data)
.
Use event.preventDefault()
as,
submitHandler: function(ev, form) { //I dont know what this form object is doing here, add event object, ev.
var d = $("#form_contact").serialize();
$.ajax({
url: '/assets/php/index.php',
type: 'POST',
//dataType: 'text',
data: d,
success: function(data) {
//$('#form_contact').hide();
$("#thanks").text("Thank you for your message. I will get back to you shortly.");
$("#form_contact")[0].reset(); // To reset form fields on success.
//return false; <-- commented it out.
}
})
//: <-- commented this colon character
ev.preventDefault(); //add it here to prevent the form from submitting
}
Please read out the comments for further clarification and I don't think you need that other return false
either. I've already removed one, chaeck the answer code.