IntricatePixels
IntricatePixels

Reputation: 1229

jquery call form ajax submission after validation is complete

I have a form and I'm using the jQuery validate plugin to validate the form. I want to call the ajax code to submit the form after the validation piece is complete.

HOW DO I:

// 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;
}

Upvotes: 0

Views: 4302

Answers (2)

CodyRob
CodyRob

Reputation: 249

This should work for you.

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

});

Upvotes: 2

Intelekshual
Intelekshual

Reputation: 7566

It's right there in the documentation.

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

Upvotes: 3

Related Questions