Ajax post with jQuery validation plugin not working

I use the jQuery validation plugin to validate the form, I need to display an error / error message after submitting without reloading the page. But every time I submit a form, it reloads the page. Also, even when the data appears in the database, a "error" warning appears.

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();
     } 

});
+4
source share
1 answer

I think your problem is here

 data: $(#myform).serialize()

change it to

 data: $(this).serialize()
+2
source

All Articles