dongxun5349
dongxun5349
2012-02-19 20:55

AJAX Jquery PHP表单验证

I would like to create a comment form based on the jquery validation plugin (http://docs.jquery.com/Plugins/Validation). How do I configure the form to submit using AJAX? Right now I cant get the form to submit without going to the next page (process.php). I want it to stay on the form page.

The code is pretty much straight from jquery currently.

<script>
    $(document).ready(function () {
        $("#commentForm").submit(function () {
            if ($("#commentForm").validate()) {
                $.ajax({
                    type: 'POST',
                    url: 'process.php',
                    data: $(this).serialize(),
                    success: function (returnedData) {
                        $('#commentForm').append(returnedData);
                    }
                });
            }
            return false;
        });
    });
</script>


<form class="cmxform" id="commentForm" method="POST" action="process.php">
<label for="cname">Name</label>
<em>*</em><input id="cname" name="name" size="25" class="required" minlength="2" />

<label for="cemail">E-Mail</label>
<em>*</em><input id="cemail" name="email" size="25"  class="required email" />

<label for="curl">URL</label>
<em>  </em><input id="curl" name="url" size="25"  class="url" value="" />
<label for="ccomment">Your comment</label>
<em>*</em><textarea id="ccomment" name="comment" cols="22"  class="required"></textarea>

<input class="submit" type="submit" value="Submit"/>

And the php is pretty standard too:

<?php

$to      = 'sdfsadfssfasd@gmail.com';
$subject = 'the subject';
$message = 'hello';
$headers = 'From: webmaster@example.com' . "
" .
'Reply-To: webmaster@example.com' . "
" .
'X-Mailer: PHP/' . phpversion();

mail($to, $subject, $message, $headers);

print "Form submitted successfully: <br>Your name is <b>".$_POST['cname']."</b> and your email is <b>".$_POST['email']."</b><br>";
?>

Thanks for any help.

  • 点赞
  • 写回答
  • 关注问题
  • 收藏
  • 复制链接分享
  • 邀请回答

1条回答

  • doushi5913 doushi5913 9年前
    $(document).ready(function(){
        $("#commentForm").submit(function(){
            if($("#commentForm").validate()){
                $.ajax({
                    type: 'POST',
                    url: 'process.php',
                    data: $(this).serialize(),
                    success: function(returnedData){
                        alert(returnedData);
                    }
                });
            }
            return false;
        });
    });
    
    点赞 评论 复制链接分享

为你推荐