1

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();
Naren Verma
  • 2,205
  • 5
  • 38
  • 95

1 Answers1

0

You need to move your submit function contents into your submit handler:

submitHandler: function ( form ) {
        $.ajax( {
          type: 'POST',
          url: 'demo2.php',
          data: $( '#form_sub' ).serialize(),
          success: function () {
            $( '.success' ).fadeIn( 200 ).show();
          }
        });
      }
Taha Paksu
  • 15,371
  • 2
  • 44
  • 78
  • Thanks for replying Mr.Taha Paksu. Working for me. I need one more help in this. Can we make the fields empty after submitting the form? Because now I am submitting the form but records are also showing in the fields. – Naren Verma May 16 '17 at 06:32
  • use `$("#form_sub").find("input, select").val("");` and if you also use textarea, add this too `$("#form_sub").find("textarea").text("");` – Taha Paksu May 16 '17 at 06:34
  • Should I add Inside success function? – Naren Verma May 16 '17 at 06:37
  • I tried below code inside Success function and working perfectly $('input[type="text"], input[type="email"] ,textarea').val(''); – Naren Verma May 16 '17 at 07:09