当我异步提交表单时,如何显示php错误消息?

时间:2015-06-10 15:56:58

标签: javascript php jquery ajax forms

我正在使用phpMailer通过AJAX发送电子邮件。

所以我需要做的是发送邮件并从submit.php获取错误消息并将其显示在contact.php

此时每次提交都会显示。即使它确实没有发送消息。

contact.php

    <div class="contact-form">
        <div class="container">
            <h2>We'd love to hear from you.</h2>
            <p>Get in touch and lets kickstart your project!</p>
            <form action="/submit" method="post" class="form">
                <label>
                <input type="text" name="name" placeholder="Name">
                </label>
                <label>
                <input type="text" name="company" placeholder="Company">
                </label>
                <label>
                  <input type="text" name="phone" placeholder="Phone">
                </label>
                <label>
                  <input type="text" name="email" placeholder="Email" required>
                </label>
                <label>
                  <textarea name="message" placeholder="Tell us about your project!" required></textarea>
                </label>
                <input class="submit" type="submit" value="Submit">
                <div id="loader"></div>
                <span class="sent">Your message has been sent!</span>
                <span class="not-sent">Your message has been sent!</span>
            </form> 
        </div>
    </div>


    <script> 
        // wait for the DOM to be loaded 
        $(document).ready(function() { 
            // bind 'myForm' and provide a simple callback function 
            $('.form').ajaxForm(function() { 

            }); 
        }); 

    $(document).ready(function(){
        var $loading = $('#loader').hide();
        $(document)
          .ajaxStart(function () {
            $loading.show();
          })
          .ajaxStop(function () {
            $loading.hide();
          });
    }); 

    $(document).ready(function(){
        var $loading = $('.sent').hide();
        $(document)
          .ajaxStart(function () {
            $loading.hide();
          })
          .ajaxStop(function () {
            $loading.show();
          });
    });

    $(document).ready(function(){
        var $loading = $('.submit').show();
        $(document)
          .ajaxStart(function () {
            $loading.hide();
          })
          .ajaxStop(function () {
            $loading.show();
          });
    });

    </script> 

submit.php

    <?php
    require 'libs/phpmailer/PHPMailerAutoload.php';

    $mail = new PHPMailer;


    $name = $_POST['name'];
    $company = $_POST['company'];
    $phone = $_POST['phone'];
    $email = $_POST['email'];
    $message = $_POST['message'];

    $mail->isSMTP();                                      // Set mailer to use SMTP
    $mail->Host = 'mail.metalink.co.za';  // Specify main and backup SMTP servers
    $mail->SMTPAuth = true;                               // Enable SMTP authentication
    $mail->Username = 'info@website.com';                 // SMTP username
    $mail->Password = 'pass';                           // SMTP password
    $mail->SMTPSecure = 'tls';                            // Enable TLS encryption, `ssl` also accepted
    $mail->Port = 25;                                    // TCP port to connect to

    $mail->From = $email = $_POST['email'];
    $mail->FromName = $name = $_POST['name'];
    $mail->addAddress('info@website.com', 'website');     // Add a recipient
    $mail->addReplyTo($email = $_POST['email']);

    $mail->WordWrap = 50;                                 // Set word wrap to 50 characters
    $mail->addAttachment('/var/tmp/file.tar.gz');         // Add attachments
    $mail->addAttachment('/tmp/image.jpg', 'new.jpg');    // Optional name
    $mail->isHTML(true);                                  // Set email format to HTML

    $mail->Subject = 'Website Response Form';
    $mail->AltBody = 'To view the message, please use an HTML compatible email viewer!';
    $mail->Body =    "<span><p><strong>Name - </strong> {$name} </p></span>
                      <p><strong>Company - </strong> {$company} </p>
                      <p><strong>Phone - </strong> {$phone} </p>
                      <p><strong>Email - </strong> {$email} </p>
                      <p><strong>Message - </strong> {$message} </p>";


    if(!$mail->send()) {
        echo '<span class="not-sent">Invalid Email</span>';
        //echo 'Mailer Error: ' . $mail->ErrorInfo;
    } else {
        echo '<span class="sent">Your message has been sent!</span>';
    }
    ?>

1 个答案:

答案 0 :(得分:1)

您需要生成JS可以解析的响应。这是一个简单的例子。您还应该考虑设置正确的内容类型和响应代码。

if(!$mail->send()) {
    echo json_encode([
        'success' => false,
        'message' => "Invalid Email"
    ]);
    //echo 'Mailer Error: ' . $mail->ErrorInfo;
} else {
    echo json_encode([
        'success' => true,
        'message' => "Your message has been sent!"
    ]);
}

然后,您应该能够使用回调方法在JS中解析此响应。

$('.form').ajaxForm(function(callback) { 
    console.log(callback);
});