Duahs Duahs - 1 year ago 68
jQuery Question

How to submit and validate a form via ajax

Please I am trying to simultaneously submit and validate my form to my database through the use of Ajax, but it is not working for me.
Here is my jquery


//Ajax to process the form
type: "POST",
url: "process.php",
data: { firstname: $("#firstname").val()},
success: function(){
return false;

The problem is when I submit the form,the Ajax form submit to itself.
Please What is the right way to use the jquery validate and $.ajax together?

Answer Source

Try this (working for me as expected):

HTML Form:

<link rel="stylesheet" href="http://jquery.bassistance.de/validate/demo/css/screen.css" />
<script src="http://jquery.bassistance.de/validate/lib/jquery.js"></script>
<script src="http://jquery.bassistance.de/validate/jquery.validate.js"></script>
// JQuery Script to submit Form
$(document).ready(function () {
        submitHandler : function () {
            // your function if, validate is success
                type : "POST",
                url : "process.php",
                data : $('#commentForm').serialize(),
                success : function (data) {

<form class="cmxform" id="commentForm" method="get" action="">
            <label for="cname">Name (required, at least 2 characters)</label>
            <input id="cname" name="name" minlength="2" type="text" required />
                <label for="cemail">E-Mail (required)</label>
                <input id="cemail" type="email" name="email" required />
                <label for="curl">URL (optional)</label>
                <input id="curl" type="url" name="url" />
                <label for="ccomment">Your comment (required)</label>
                <textarea id="ccomment" name="comment" required></textarea>
                <input class="submit" type="submit" value="Submit" />

<div id="message"></div>

PHP Code:

echo $_POST['email'];
Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download