I am using Jquery validation plugin to validate form, I need to display success/error message after submission without reloading page. But everytime I submit form, page reloads. Also even when data appears on database, "error" alert keeps coming.
index.php
<?php
function register() {
$name = $_POST['name'];
$mail = $_POST['email'];
$query = "INSERT INTO table_name (name,email) VALUES ('$name','$email')";
$data = mysql_query($query)or die(mysql_error());
echo json_encode($data);
}
if(isset($_POST['submit'])) {
register();
}
?>
Javascript code:
$("#myform").validate({
//rules, messages go here
submitHandler: function(event) {
$.ajax({
url: "index.php",
type: "POST",
data: $(#myform).serialize(),
dataType: 'json',
success: function() {
alert("Thank you!");
},
error: function() {
alert("Error. Try again please!");
}
});
event.preventDefault();
}
});
i think your problem is here
data: $(#myform).serialize()
change it to
data: $(this).serialize()
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With