Javascript 表单发送消息两次

Javascript 表单发送消息两次,javascript,php,jquery,forms,Javascript,Php,Jquery,Forms,我正在调整一个自由形式,它工作得很好,但它发送电子邮件两次,并在完成两次后写消息。我试图用一个“button”类型的输入标记替换表单中的按钮和输入标记,但它兑现了。还有一个问题是,每次单击都会运行脚本并发送下一条消息,因此,如果我在一瞬间单击几次,它将发送大量电子邮件。我应该在php或js中禁止这种行为吗 <?php if(isset($emailSent) && $emailSent == true) { ?> <p class

我正在调整一个自由形式,它工作得很好,但它发送电子邮件两次,并在完成两次后写消息。我试图用一个“button”类型的输入标记替换表单中的按钮和输入标记,但它兑现了。还有一个问题是,每次单击都会运行脚本并发送下一条消息,因此,如果我在一瞬间单击几次,它将发送大量电子邮件。我应该在php或js中禁止这种行为吗

<?php if(isset($emailSent) && $emailSent == true) { ?>
                <p class="info">Your email was sent</p>
            <?php } else { ?>

                <div class="desc">
                    <h2>Contact Us</h2>
                </div>

                <div id="contact-form">
                    <?php if(isset($hasError) || isset($captchaError) ) { ?>
                        <p class="alert">Error submitting the form</p>
                    <?php } ?>

                    <form id="contact-us" action="contact.php" method="post">
                        <div class="formblock">
                            <label class="screen-reader-text">Name</label>
                            <input type="text" name="contactName" id="contactName" value="<?php if(isset($_POST['contactName'])) echo $_POST['contactName'];?>" class="txt requiredField" placeholder="Name:" />
                            <?php if($nameError != '') { ?>
                                <br /><span class="error"><?php echo $nameError;?></span> 
                            <?php } ?>
                        </div>

                        <div class="formblock">
                            <label class="screen-reader-text">Email</label>
                            <input type="email" name="email" id="email" value="<?php if(isset($_POST['email']))  echo $_POST['email'];?>" class="txt requiredField email" placeholder="Email:" />
                            <?php if($emailError != '') { ?>
                                <br /><span class="error"><?php echo $emailError;?></span>
                            <?php } ?>
                        </div>

                        <div class="formblock">
                            <label class="screen-reader-text">Message</label>
                             <textarea name="comments" id="commentsText" class="txtarea requiredField" placeholder="Message:"><?php if(isset($_POST['comments'])) { if(function_exists('stripslashes')) { echo stripslashes($_POST['comments']); } else { echo $_POST['comments']; } } ?></textarea>
                            <?php if($commentError != '') { ?>
                                <br /><span class="error"><?php echo $commentError;?></span> 
                            <?php } ?>
                        </div>
                        <button name="submit" type="submit" class="subbutton">Send us Mail!</button>
                            <input type="hidden" name="submitted" id="submitted" value="true" />
                    </form>         
                </div>

            <?php } ?>
        </div>
    </div><!-- End #contact -->

<script type="text/javascript">
    <!--//--><![CDATA[//><!--
    $(document).ready(function() {
        $('form#contact-us').submit(function() {
            $('form#contact-us .error').remove();
            var hasError = false;
            $('.requiredField').each(function() {
                if($.trim($(this).val()) == '') {
                    var labelText = $(this).prev('label').text();
                    $(this).parent().append('<span class="error">Your forgot to enter your '+labelText+'.</span>');
                    $(this).addClass('inputError');
                    hasError = true;
                } else if($(this).hasClass('email')) {
                    var emailReg = /^([\w-\.]+@([\w-]+\.)+[\w-]{2,4})?$/;
                    if(!emailReg.test($.trim($(this).val()))) {
                        var labelText = $(this).prev('label').text();
                        $(this).parent().append('<span class="error">Sorry! You\'ve entered an invalid '+labelText+'.</span>');
                        $(this).addClass('inputError');
                        hasError = true;
                    }
                }
            });
            if(!hasError) {
                var formInput = $(this).serialize();
                $.post($(this).attr('action'),formInput, function(data){
                    $('form#contact-us').slideUp("fast", function() {                  
                        $(this).before('<p class="tick"><strong>Thanks!</strong> Your email has been delivered. Huzzah!</p>');
                    });
                });
            }

            return false;   
        });
    });
    //-->!]]>
</script>

<?php 
error_reporting(E_ALL ^ E_NOTICE); // hide all basic notices from PHP

//If the form is submitted
if(isset($_POST['submitted'])) {

    // require a name from user
    if(trim($_POST['contactName']) === '') {
        $nameError =  'Forgot your name!'; 
        $hasError = true;
    } else {
        $name = trim($_POST['contactName']);
    }

    // need valid email
    if(trim($_POST['email']) === '')  {
        $emailError = 'Forgot to enter in your e-mail address.';
        $hasError = true;
    } else if (!preg_match("/^[[:alnum:]][a-z0-9_.-]*@[a-z0-9.-]+\.[a-z]{2,4}$/i", trim($_POST['email']))) {
        $emailError = 'You entered an invalid email address.';
        $hasError = true;
    } else {
        $email = trim($_POST['email']);
    }

    // we need at least some content
    if(trim($_POST['comments']) === '') {
        $commentError = 'You forgot to enter a message!';
        $hasError = true;
    } else {
        if(function_exists('stripslashes')) {
            $comments = stripslashes(trim($_POST['comments']));
        } else {
            $comments = trim($_POST['comments']);
        }
    }

    // upon no failure errors let's email now!
    if(!isset($hasError)) {

        $emailTo = 'example@example.com';
        $subject = 'Submitted message from '.$name;
        $sendCopy = trim($_POST['sendCopy']);
        $body = "Name: $name \n\nEmail: $email \n\nComments: $comments";
        $headers = 'From: ' .' <'.$emailTo.'>' . "\r\n" . 'Reply-To: ' . $email;

        mail($emailTo, $subject, $body, $headers);
        mail($email, $subject, $body, $headers);

        // set our boolean completion value to TRUE
        $emailSent = true;
    }
}
?>

您的电子邮件已发送

联系我们 提交表单时出错

名称
submithandler函数接收一个名为
event
的参数。当检测到验证错误时,需要调用
event.preventDefault()
,以便表单不会提交

$(document).ready(function() {
    $('form#contact-us').submit(function(event) {
        // you detect a validation error...
        hasError = true;

        // more stuff on submit...

        // at the end of the function
        if (hasError) {
            event.preventDefault();
        }
    });

邮件函数被调用了两次!“$(文档).ready(函数(){$('form#contact-us')。submit(函数()…”加载页面时提交表单,提交按钮也可以。使用其中一个。@piddl0r一个是自动回复,另一个是默认电子邮件地址。user1522901仅绑定表单操作。user3654049,您需要阻止表单的默认操作,否则您将执行ajax调用,然后页面将继续inue和表单将正常提交(因此发送了2封邮件)。请尝试
$('form#contact us')。提交(函数(e){e.preventDefault();…
而不是
返回false;
@piddl0r yes,contact.php中的mail函数被调用两次,因为它将电子邮件发送到主机并复制到的用户form@Pete它可以工作,一封电子邮件,但也会停止页面的操作,我必须重新加载iTunes。这个解决方案会中断表单的操作,并且没有确认消息,尽管消息发送正确。