2

I am trying to use jQuery Validation plugin on my website. I need to validate two separate forms and use ajax to submit them to two different PHP pages. I am new to JavaScript, but have done a lot of research regarding this, however, I am still stuck.

This is what I have come up with so far... How can I validate and submit one form to processA.php and the second form to processB.php. Each form has different fields. Is it possible to add a second submitHandler?

$("form").each(function() {
    $(this).validate({
        submitHandler: function(form) {
            $.ajax({
                type    : 'POST',
                url     : 'processA.php',// write code to send mail in mail.php
                data    : $(form).serialize(),
                cache   : false,
                dataType: 'text',
                success : function (serverResponse) { 
                      alert('mail sent successfully.'); 
                },
                error   : function (jqXHR, textStatus, errorThrown) {
                      alert('error sending mail');
                }
            });
            return false; // Temporary
        }
    });
});
1
  • Please only use back-ticks for inline code, not for code blocks. Use the {} button to format a block of code. Commented Sep 2, 2014 at 18:51

1 Answer 1

1

No, you cannot have two different submitHandler callback functions within one instance of the .validate() method. When you call the .validate() method within a jQuery .each()... you are intentionally applying the same options to every form targeted by your .each().


Instead, put the corresponding URL within the action attribute of each form tag...

<form action="processA.php" ...

<form action="processB.php" ...

The use jQuery's .attr() method to get the correct URL from each action...

$("form").each(function() {
    $(this).validate({
        submitHandler: function(form) {
            $.ajax({
                ....
                url: $(form).attr('action'), // <- the correct URL for this form
                ....
            });
            return false; // Temporary
        }
    });
});
Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.