简体   繁体   中英

Ajax form submission in Jquery submitHandler is not working

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

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

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

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

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

$('#submitButton').click(function(event) {
    event.preventDefault();  

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM