SMTP PHP表单成功但成功消息未显示

时间:2013-11-08 19:09:26

标签: php jquery ajax smtp sendgrid

我的代码工作正常,表单数据已发送。但是,重置表单和显示/淡入成功消息的代码不是

<?php 
    require("class.phpmailer.php");
    $mail = new PHPMailer();

    // Validation without reload
    if ($_POST) { 

        // SMTP & Sendgrid settings
        $mail->IsSMTP();
        $mail->Host = "smtp.site.com";
        $mail->Port = "587";
        $mail->SMTPAuth = "true";   // Enable SMTP authentication
        $mail->Username = "username";  
        $mail->Password = "password";
        $mail->SMTPSecure = ''; // Enable encryption, 'ssl' also accepted

        // Email headers and body
        $mail->SetFrom("email@email.com");
        $mail->AddAddress("email@email.com");

        $mail->Subject  = "Message from site.com";
        $mail->WordWrap = 50;

        // Form fields
        $FirstName = $_POST['FirstName'];
        $LastName = $_POST['LastName'];
        $Company = $_POST['Company'];
        $JobTitle = $_POST['JobTitle'];
        $Email = $_POST['Email'];
        $Phone = $_POST['Phone'];
        $Message = $_POST['Message'];

        // Assign variables to body. ALWAYS after the variables are assigned.
        $mail->Body     = "You have a new message from your contact form on ShipmentHQ.com \n First Name: $FirstName \n Last Name: $LastName \n Company: $Company \n Job Title: $JobTitle \n Email: $Email \n Phone: $Phone \n Message: $Message";

        if(!$mail->Send()) {
          alert('Thanks, your message has been sent.');
          echo 'Mailer error: ' . $mail->ErrorInfo;
        } 
        else {
          alert('Your message has not been sent.');
        }
    }
?>

我做错了什么? if(!$ mail-&gt; Send()){来自php甚至不起作用,有没有办法重构它所以我不需要javascript?

<script> 
    $(document).ready(function() {
        $("#ContactForm").validate({
            submitHandler: function() {
                //submit the form
                $.post("<?php echo $_SERVER[PHP_SELF]; ?>", //post
                    $("#ContactForm").serialize(), 
                    function(data){
                      //if message is sent
                      if (data == 'Sent') {
                        $("#message").fadeIn(); //show confirmation message
                        $("#ContactForm")[0].reset(); //reset fields
                    }
                    //
                });
                return false; //don't let the page refresh on submit.
            }
        }); //validate the form
    });
    </script> 

1 个答案:

答案 0 :(得分:0)

您需要将 alert 这样包围起来[查看周围的 <script> 标签]

第二件事是......你没有正确地解释消息,if(!$mail->Send())它应该说Your message has not been sent.,但你正在做另一种方式。 [别担心我已经为你修改过了;)]

 if(!$mail->Send())
        {
          echo "<script>alert('Your message has not been sent.')</script>";
          echo 'Mailer error: ' . $mail->ErrorInfo;
        } 
 else
        {
     echo "<script>alert('Thanks, your message has been sent.')</script>";
        }