Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Ajax form submission with Jquery validation plugin is not working

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

});
like image 937
user3793667 Avatar asked Oct 31 '22 06:10

user3793667


1 Answers

i think your problem is here

 data: $(#myform).serialize()

change it to

 data: $(this).serialize()
like image 112
user2460074 Avatar answered Nov 10 '22 02:11

user2460074