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

标签 javascript php jquery ajax forms

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

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

目前,每个提交都会显示。消息已发送,即使它确实没有发送。

联系.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>';
    }
    ?>

最佳答案

您需要生成 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);
}); 

关于javascript - 当我异步提交表单时,如何显示 php 错误消息?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/30761443/

相关文章:

尝试使用 stat() 或 filemtime() 时出现 PHP 警告

javascript - 如何将选择多个选项字段插入到 forms.js?

javascript - ckeditor textarea 自定义与 jquery 拖放

javascript - 使用相同的时间戳 firestore 在不同页面上返回相同的结果

javascript - 如何解决 “Uncaught TypeError: Cannot read property ' checked' of null”

javascript - Playground.js 未渲染

php - 根据输入参数值在phpdoc中指定@return类型

javascript - 如何在javascript中调用动态命名的对象及其方法?

javascript - 计算丢失的项目后将新数组添加到 JSON 对象

javascript - 如何从 JSON 创建数组?