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

Posted

技术标签:

【中文标题】异步提交表单时如何显示 php 错误消息?【英文标题】:How do I show php error message when I'm submitting the form asynchronously? 【发布时间】:2015-08-26 00:09:27 【问题描述】:

我正在使用 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> 

提交.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】:

你需要生成一个 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);
); 

【讨论】:

以上是关于异步提交表单时如何显示 php 错误消息?的主要内容,如果未能解决你的问题,请参考以下文章

使用php提交ajax表单

PHP - 如何在提交后隐藏表单

验证 php 表单 - 如何在表单上显示错误消息

表单提交成功后如何在 div 中创建成功消息?

如何防止引导验证在表单提交之前显示错误消息?

成功提交表单后如何在div中创建成功消息?