联系表单上的错误通过jquery ajax提交

时间:2013-04-02 16:44:29

标签: php jquery html ajax forms

基于此question我必须重写我的联系表单脚本。 目标是有一个标有send的发送按钮。点击后它应该显示sending,直到php脚本完成。完成后,它应显示sent

这就是我的简单形式:

<form id="contactForm" action="mail.php" method="post">
  <input type="text" id="name" name="name" placeholder="Name" required><br />
  <input type="text" id="email" name="email" placeholder="Mail" required><br />
  <textarea name="message" id="message" placeholder="Nachricht" required></textarea><br />
  <button name="submit" type="submit" id="submit">send</button>
</form>

这是标签更改的jquery脚本和ajax submit。

<script>
            $( init );
            function init() {
                $('#contactForm').submit( submitForm );
            }
            function submitForm() {
                var contactForm = $(this);
                if ( !$('#name').val() || !$('#email').val() || !$('#message').val() ) {
                    $('#submit').html('error');
                } else {
                    $('#submit').html('sending');
                    $.ajax( {
                      url: contactForm.attr( 'action' ) + "?ajax=true",
                      type: contactForm.attr( 'method' ),
                      data: contactForm.serialize(),
                      success: submitFinished
                    } );
                }
                return false;
            }
            function submitFinished( response ) {
                response = $.trim( response );
                if ( response == "success" ) {
                    $('#submit').HTML = ('sent');
                } else {
                  $('#submit').html('error');
                }
            }
        </script>

mail.php:

<?php 

define( "RECIPIENT_NAME", "John Doe" );
define( "RECIPIENT_EMAIL", "john@doe.com" );
define( "EMAIL_SUBJECT", "Subject" );

$success = false;

$name = isset( $_POST['name'] ) ? preg_replace( "/[^\.\-\' a-zA-Z0-9]/", "", $_POST['name'] ) : "";
$email = isset( $_POST['email'] ) ? preg_replace( "/[^\.\-\_\@a-zA-Z0-9]/", "", $_POST['email'] ) : "";
$message = isset( $_POST['message'] ) ? preg_replace( "/(From:|To:|BCC:|CC:|Subject:|Content-Type:)/", "", $_POST['message'] ) : "";

if ( $name && $email && $message ) {
  $recipient = RECIPIENT_NAME . " <" . RECIPIENT_EMAIL . ">";
  $headers = "Von: " . $name . " <" . $email . ">";
  $success = mail( $recipient, EMAIL_SUBJECT, $message, $headers );
}

if ( isset($_GET["ajax"]) ) {
  echo $success ? "success" : "error";
} else {
 //add html for javascript off user
}
?>

它提交正确,我收到邮件,但我没有将标签更改为sent。它卡在sending。 我的代码有什么想法或建议吗?

最好的问候 dennym

3 个答案:

答案 0 :(得分:3)

错误在这一行:

$('#submit').HTML = ('sent');

将其更改为:

$('#submit').html('sent');

答案 1 :(得分:2)

$('#submit').HTML = ('sent');

应该是

$('#submit').html('sent');

就像你在其他地方一样。

答案 2 :(得分:2)

你必须改变

$('#submit').HTML = ('sent');

为:

$('#submit').html('sent');

在您的函数submitFinished();