【问题标题】:PHP Form Submit Without RefreshPHP表单提交不刷新
【发布时间】:2012-08-08 07:07:21
【问题描述】:

我在创建此表单时完成了教程,并对其进行了编辑和格式化以匹配我的网站。原始表单按照我想要的方式工作,而我的工作方式除了在提交表单时没有向上滑动,而是页面刷新。我已经对代码进行了很多次比较,并查看了所有地方,无法弄清楚我更改或遗漏了什么导致我刷新页面。任何帮助将不胜感激。我已经花了好几个小时来解决这个问题,而且我敢肯定这是一件小事。

这里是原始教程:http://www.hongkiat.com/blog/ajax-html5-css3-contact-form-tutorial/

这是我的代码:

标头中的PHP:

<?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 =  '<strong>WARNING:</strong> Please provide your full name.'; 
    $hasError = true;
} else {
    $name = trim($_POST['contactName']);
}

// need valid email
if(trim($_POST['email']) === '')  {
    $emailError = '<strong>WARNING:</strong> Please provide an email address.';
    $hasError = true;
} else if (!preg_match("/^[[:alnum:]][a-z0-9_.-]*@[a-z0-9.-]+\.[a-z]{2,4}$/i", trim($_POST['email']))) {
    $emailError = 'Please provide a valid email address.';
    $hasError = true;
} else {
    $email = trim($_POST['email']);
}

// require a phone from user
if(trim($_POST['phone']) === '') {
    $phoneError =  '<strong>WARNING:</strong> Please provide a phone number.'; 
    $hasError = true;
} else {
    $phone = trim($_POST['phone']);
}

// we need at least some content
if(trim($_POST['comments']) === '') {
    $commentError = '<strong>WARNING:</strong> Please provide 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 = 'myemail@gmail.com';
    $subject = 'Submitted message from '.$name;
    $sendCopy = trim($_POST['sendCopy']);
    $body = "Name: $name \n\nEmail: $email \n\nPhone: $phone \n\nComments: $comments";
    $headers = 'From: ' .' <'.$email.'>' . "\r\n" . 'Reply-To: ' . $email;

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

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

PHP 表单:

            <div class="separator">
                <h5>Keep in touch</h5>
                <div class="sep_line"></div><!-- separator line -->
            </div>

            <div class="clear"></div>


            <div class="twoThirds">

        <?php if(isset($emailSent) && $emailSent == true) { ?>
            <div class="Note Success hideit">
            <p><strong>SUCCESS: </strong>Your message has been sent.</p>
            </div>
        <?php } else { ?>

                <div id="respon">

                <?php if(isset($hasError) || isset($captchaError) ) { ?>
                    <div class="Note Failure hideit">
                    <p><strong>FAILURE: </strong>Error submitting the message.</p>
                    </div>
                <?php } ?>

                    <form action="contact.php" method="post" id="contact-form">    

                        <label for="name">
                            Name:  *                    </label>
                        <input type="text" name="contactName" id="contactName" value="<?php if(isset($_POST['contactName'])) echo $_POST['contactName'];?>" size="22" tabindex="1" class="nameInput">
                        <?php if($nameError != '') { ?>
                            <br><div class="Note Warning hideit"><p><?php echo $nameError;?></p></div> 
                        <?php } ?>
                       <label for="email">
                            Email:  *                   </label>
                        <input type="text" name="email" id="email" value="<?php if(isset($_POST['email']))  echo $_POST['email'];?>" size="22" tabindex="2" class="emailInput">  
                        <?php if($emailError != '') { ?>
                            <br><div class="Note Warning hideit"><p><?php echo $emailError;?></p></div>
                        <?php } ?>
                        <label for="phone">
                            Phone:  *               </label>
                        <input type="text" name="phone" id="phone" value="<?php if(isset($_POST['phone']))  echo $_POST['phone'];?>" size="22" tabindex="3" class="webInput">
                        <?php if($phoneError != '') { ?>
                            <br><div class="Note Warning hideit"><p><?php echo $phoneError;?></p></div> 
                        <?php } ?>
                        <label for="message">
                            Your Message:   *               </label>
                        <textarea name="comments" id="commentsText" tabindex="4" class="messageInput"><?php if(isset($_POST['comments'])) { if(function_exists('stripslashes')) { echo stripslashes($_POST['comments']); } else { echo $_POST['comments']; } } ?></textarea>
                        <?php if($commentError != '') { ?>
                            <br><div class="Note Warning hideit"><p><?php echo $commentError;?></p></div> 
                        <?php } ?>                            
                        <br>

                        <input name="reset" class="button" type="reset" id="reset" tabindex="5" value="Reset">
                        <input name="submit" class="button" type="submit" id="submit" tabindex="6" value="Submit">
                        <input type="hidden" name="submitted" id="submitted" value="true" />                            
                    </form>

                </div>
        <?php } ?>


        </div><!-- end main contact-us -->

Javascript:

<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="Note Warning hideit">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="Note Warning hideit">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="Note Success hideit"><strong>SUCCESS: </strong>Your message has been sent.</p>');
                });
            });
        }

        return false;   
    });

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

【问题讨论】:

  • 在刷新前检查是否抛出错误,可能有错误导致代码无法到达return false部分

标签: php javascript forms refresh


【解决方案1】:

解决方法很简单,

主要是您缺少为您提交的表单指定正确的id

<form action="contact.php" method="post" id="contact-form">

应该在哪里

<form action="contact.php" method="post" id="contact-us">

表单中缺少一些属性,您在 javascript 中选择了这些属性

例如。

  • .requiredField
  • .error

也尝试纠正这些问题。

编辑

粗略编辑的表单块

<form action="contact.php" method="post" id="contact-us">    

    <label for="name">
        Name:  *                    </label>
    <input type="text" name="contactName" id="contactName" value="<?php if (isset($_POST['contactName'])) echo $_POST['contactName']; ?>" size="22" tabindex="1" class="nameInput requiredField">
    <?php if ($nameError != '') { ?>
        <br><div class="error"><p><?php echo $nameError; ?></p></div> 
    <?php } ?>
    <label for="email">
        Email:  *                   </label>
    <input type="text" name="email" id="email" value="<?php if (isset($_POST['email'])) echo $_POST['email']; ?>" size="22" tabindex="2" class="email requiredField">  
    <?php if ($emailError != '') { ?>
        <br><div class="error"><p><?php echo $emailError; ?></p></div>
    <?php } ?>
    <label for="phone">
        Phone:  *               </label>
    <input type="text" name="phone" id="phone" value="<?php if (isset($_POST['phone'])) echo $_POST['phone']; ?>" size="22" tabindex="3" class="webInput requiredField">
    <?php if ($phoneError != '') { ?>
        <br><div class="error"><p><?php echo $phoneError; ?></p></div> 
    <?php } ?>
    <label for="message">
        Your Message:   *               </label>
    <textarea name="comments" id="commentsText" tabindex="4" class="messageInput requiredField"><?php if (isset($_POST['comments'])) {
        if (function_exists('stripslashes')) {
            echo stripslashes($_POST['comments']);
        } else {
            echo $_POST['comments'];
        }
    } ?></textarea>
    <?php if ($commentError != '') { ?>
            <br><div class="error"><p><?php echo $commentError; ?></p></div> 
    <?php } ?>                            
    <br>

    <input name="reset" class="button" type="reset" id="reset" tabindex="5" value="Reset">
    <input name="submit" class="button" type="submit" id="submit" tabindex="6" value="Submit">
    <input type="hidden" name="submitted" id="submitted" value="true" />                            
</form>​

又一次编辑

在你的JS文件更改中,

$(this).parent().append('<span class="Note Warning hideit">

$(this).parent().append('<span class="error">

$(this).before('<p class="Note Success hideit">

$(this).before('<p class="tick">

如教程中所述。

【讨论】:

  • 更改表单 ID 确实解决了刷新问题,但现在一些格式消失了,即使表单为空白,它也表示提交成功。我真的不太了解javascript,我真的需要它还是我可以只使用php而仍然没有刷新页面?
  • @AndrewWilliams 当然,不。你不能没有JS。正如我提到的,由于表单缺少一些属性,您会收到成功消息。因此hasError 总是false。对于格式,请根据您在表单中所做的更改修改 css 文件。
  • 你能举个例子说明我缺少什么吗?
  • 现在工作好多了,谢谢,现在唯一不工作的是 hideit,你可以点击出现的错误,它就会消失,没什么大不了的,但是另一个是..一旦出现错误,直到成功提交才会消失,例如,如果我立即单击提交,我会收到 4 个错误,如果我更正了所有错误,但电子邮件地址无效,它会显示为另一个错误在其他 4 个之上,它们只是继续相互构建,如果你点击重置它会清除错误。
  • 是的,谢谢您,现在一切正常!我想重置以清除错误,但不是那么大的问题。再次感谢您的帮助!
猜你喜欢
  • 1970-01-01
  • 2013-12-21
  • 2017-04-09
  • 1970-01-01
  • 2011-11-18
  • 2013-07-10
  • 2014-03-03
  • 1970-01-01
相关资源
最近更新 更多