验证完成后,jquery调用表单ajax提交

时间:2011-03-07 21:18:38

标签: javascript jquery ajax jquery-validate

我有一个表单,我正在使用j Query validate插件来验证表单。我想在验证片完成后调用ajax代码提交表单。

我如何:

// CALL THE postform code if the form validation is complete?
// THIS IS THE FORM VALIDATION CODE
    $(document).ready(function() {
     $("#myForm").validate({
         rules: {
            password: "required",
        password_confirm: {
        equalTo: "#password"
        }                   
        }                
    });
    });


// THIS IS THE AJAX FORM SUBMISSION CODE
// I WANT THIS CODE EXECUTED IF CODE ABOVE IS OK
function postform()
{
  dataString = $("#myForm").serialize();
  $.ajax({
      url: 'https:/www.someothersite.com'+dataString,
      type: 'GET',
      dataType: 'html',
      timeout: 9000,
      error: function(){
          alert('Error posting to other site');
      },
      success: function(html){
          window.location.href="http://www.mysite.com/?action=success";
      }
  });
  return false;
}

2 个答案:

答案 0 :(得分:3)

就在documentation

$("#myForm").validate({
    submitHandler: function(form) {
        postForm();
    }
})

答案 1 :(得分:2)

这应该适合你。

$(document).ready(function() {

    $('#myForm').validate({
        rules: {
            password: 'required'
        },
        password_confirm: {
            equal_to: 'password'
        },
        submitHandler: function() {
            var dataString = $(this).serialize();

            $.ajax({
                url: 'https://www.someothersite.com' + dataString,
                type: 'GET',
                dataType: 'html',
                timeout: 9000,
                error: function() {
                    alert('Error posting to other site');
                },
                success: function(html) {
                    window.location.href = 'https://www.mysite.com/?action=success';
                }
            });
        }
    });

});