0

I need to validate form with jQuery Validation Plugin and submit data to database without page refresh. All fields in my form are marked as required. However, fields are submitted even if they are empty. Also, page keeps refreshing.

This is my JavaScript code:

    $('#submitButton').click(function() {  
    $("#myForm").validate({
       debug: true,
       rules: {
            name: {
                required: true
            },
            user_mail: {
                required: true
            }
       },
       messages:{
           //messages     
       },
       submitHandler(function(form) {
            $.ajax({  
              type: 'POST',
              url: $(this).attr('action'),
              data: $(this).serialize(),
              dataType : 'json',
              success(function(data) {
                if (data){
                    alert("success");
                    $(this)[0].reset();
                }
              })
            });
            return false;
        });
  });
}

This is how php looks like

  <?php

    function NewUser(){ 
    $fullname = $_POST['name']; 
    $emailaddress = $_POST['user_mail']; 


    $query = "INSERT INTO my_table (fullName,emailaddress) VALUES ('$fullname','$emailaddress')"; 
    $data = mysql_query($query)or die(mysql_error()); 
    echo json_encode($data);
    } 

    if(isset($_POST['submit'])){ 
    NewUser();
    }

    ?>

This code works well, all data appears in database correctly

  • any error any console log? – Saty Apr 28 '15 at 12:15
  • looks like you are using some sort of validation plugin, would be good to include that in your question – deowk Apr 28 '15 at 12:16
  • no error on console log, it's just redirects to new page with 'true' message. Also I am using jQuery Validation Plugin –  Apr 28 '15 at 12:25

5 Answers5

0

So, preventing default button behavior via javascript is valid. BUT, I prefer just making the button type="button".

<button type="button" id="submitButton">

This will prevent form submission as well; it's a matter of preference, and I prefer it because it drives behavior via the DOM, rather than adding more jquery for stuff like this.

FYI, the default type of a button when located in a <form> is type="submit". https://stackoverflow.com/a/4667996/769971

Community
  • 1
  • 1
wholevinski
  • 3,658
  • 17
  • 23
0

(function($,W,D) { var JQUERY4U = {};

JQUERY4U.UTIL =
{
    setupFormValidation: function()
    {
        //form validation rules
        $("#formid").validate({
            rules: {

                fielname1: {required : true},
                fielname2: {required : true},
                agree: "required"
            },
            messages: {
                fielname1: {required :"<p>Please enter your fielname1</p>"  },
                fielname2: {required :"<p>Please enter your fielname2</p>"  },
                agree: "Please accept our policy"
            }               
        });
    }       
}

//when the dom has loaded setup form validation rules
$(D).ready(function($) {
    JQUERY4U.UTIL.setupFormValidation();

});

})(jQuery, window, document);

  • Why should the OP "try this"? Please add an explanation of what you did and why you did it that way not only for the OP but for future visitors to SO. – Jay Blanchard Apr 28 '15 at 12:50
  • My major problem is in Ajax submission, it just doesn't work. Validation works fine –  Apr 28 '15 at 13:04
0

try:

$('#submitButton').click(function() {  
    $("#myForm").validate({
       debug: true,
       rules: {
            name: {
                required: true
            },
            user_mail: {
                required: true
            }
       },
       messages:{
           //messages     
       },
       submitHandler: function (form) {
            $.ajax({  
              type: 'POST',
              url: $(this).attr('action'),
              data: $(this).serialize(),
              dataType : 'json',
              success(function(data) {
                if (data){
                    alert("success");
                    $(this)[0].reset();
                }
              })
            });
            return false;
       }
  });
}

and check demo from this question

Community
  • 1
  • 1
alquist42
  • 739
  • 1
  • 8
  • 21
-1

Try sticking a event.preventDefault() in the click handler:

$('#submitButton').click(function(event) {
    event.preventDefault();  
Joe Fitter
  • 1,309
  • 7
  • 11
-1

This is how the submitHandler is used. It's always good to read the docs that'd help you understand the plugin better.

submitHandler (default: native form submit) Type: Function() Callback for handling the actual submit when the form is valid. Gets the form as the only argument. Replaces the default submit.

submitHandler: function(form) {
    var $form = $(form);
    $.ajax({
        type: 'POST',
        url: $form.attr('action'),
        data: $form.serialize(),
        dataType : 'json',
        success(function(data) {
            if (data) {
                alert("success");
                $form[0].reset();
            }
        });
    });
    return false; // Not sure if you needed this.
});
lshettyl
  • 8,166
  • 4
  • 25
  • 31