使用PHPMailer发送电子邮件后,在同一页面上显示成功/失败消息,而无需重新加载或重定向页面

时间:2019-04-23 07:10:44

标签: php jquery ajax phpmailer

我创建了一个简单的html&bootstrap联系人表单,该表单由PHPMailer类支持以发送电子邮件。该程序在发送电子邮件之前可以完美运行。但是,它不会在同一页面上显示成功/失败消息,也不会清除字段。

我为演示程序编写的代码如下。请将您的解决方案附加到相同的代码,而不是自己编写另一个代码。

index.html

<form method="post" action="mail.php" id="contact-form" role="form">
                    <div class="card-header">
                        <h2 class="font-weight-bold text-center my-4">Contact us</h2>
                        <p class="text-center mx-auto mb-5">Do you have any questions? Please do not hesitate to
                            contact us directly. Our team will come back to you within
                            a matter of hours to help you.</p>
                        <div class="alert alert-success" id="success-message"><span>Thank you for contacting us. We will
                                be in touch
                                soon.</span></div>
                    </div>
                    <div class="card-body">
                        <div class="row">
                            <div class="col-md-6">
                                <div class="form-group ">
                                    <label for="name" class="is-required">Name</label>
                                    <input type="text" name="name" id="name" class="form-control" minlength="3"
                                        required>
                                </div>
                            </div>
                            <div class="col-md-6">
                                <div class="form-group ">
                                    <label for="email" class="is-required">email</label>
                                    <input type="email" name="email" id="email" class="form-control" required>
                                </div>
                            </div>
                        </div>
                        <div class="row">
                            <div class="col-md-12">
                                <div class="form-group">
                                    <label for="message" class="is-required">Message</label>
                                    <textarea name="message" id="message" rows="2" class="form-control"
                                        required></textarea>
                                </div>
                            </div>
                        </div>
                        <div class="row">
                            <div class="col-md-12">
                                <div class="text-center text-md-left">
                                    <input type="hidden" name="action" value="sendEmail" />
                                    <button id="submit-button" name="submit" type="submit" value="Send"
                                        class="btn btn-primary"><span>Send</span></button>
                                </div>
                                <div class="status" id="status"></div>
                            </div>
                        </div>
                        <div class="row">
                            <div class="col-md-12">
                                <div class="status" id="status"></div>
                            </div>
                        </div>
                    </div>
                </form>

jQuery / ajax

 <script>
        $('form').validate();
        $(document).ready(() => {
            $('#success-message').hide();
            $('form').submit((e) => {

                let formData = {
                    'name': $('#name').val(),
                    'email': $('#email').val(),
                    'message': $('#message').val(),
                    'submit': 1
                };

                $.ajax({
                    type: 'POST',
                    url: 'mail.php',
                    data: formData,
                    dataType: 'json',
                    encode: true
                }).done((data) => {
                    if (data.success) {
                        $('#success-message').show();
                    } else {
                        alert('Something went wrong. Please try again!');
                    }
                });
                e.preventDefault();
            });
        });
    </script>

mail.php

<?php
    use PHPMailer\PHPMailer\PHPMailer;
    use PHPMailer\PHPMailer\Exception;

// Load Composer's autoloader
    require 'vendor/autoload.php';
    // header('Content-Type: application/json');

    if (isset($_POST['submit'])) {
        $name = $_POST['name'];       // Sender's name
        $email = filter_var($_POST['email'], FILTER_VALIDATE_EMAIL);
        $message = $_POST['message'];    // Sender's message

        $errorEmpty = false;
        $errorEmail = false;

        if (empty($name) || empty($email) || empty($message)) {
            echo "<span class='alert alert-danger'> Name is required.</span>";
            $errorEmpty = true;
        }
        if (filter_var($email, FILTER_VALIDATE_EMAIL)) {
            echo "<span class='alert alert-danger'> Please try entering a correct email.</span>";
            $errorEmail = true;
        }




        // Instantiate PHPMailer class
        $mail = new PHPMailer(true);

        try {
            //Server settings
            $mail->SMTPDebug = 0;                                       // Enable verbose debug output
            $mail->isSMTP();                                            // Set mailer to use SMTP
            $mail->Host       = 'smtp.gmail.com';  // Specify main and backup SMTP servers
            $mail->SMTPAuth   = true;                                   // Enable SMTP authentication
            $mail->Username   = 'mymail@gmail.com';                     // SMTP username
            $mail->Password   = 'mypass';                               // SMTP password
            $mail->SMTPSecure = 'tls';                                  // Enable TLS encryption, `ssl` also accepted
            $mail->Port       = 587;                                    // TCP port to connect to

    //Recipients
            $mail->setFrom('mymail@gmail.com', 'My Name');
            $mail->addAddress($email, $name);     // Add a recipient

            $body = '<p>Hello <strong> Mr. ' . $name . '</strong> <br /><br /> We have received your enquiry "' .$message. '". <br /> We ensure you that the team is working on it. <br /><br /> Thank you. </p>';

            // Content
            $mail->isHTML(true);                                  // Set email format to HTML
            $mail->Subject = 'We received your query.';
            $mail->Body    = $body;
            // $mail->AltBody = strip_tags($body);

            $mail->send();
            // echo 'Message has been sent';
        } catch (Exception $e) {
            echo $e->errorMessage();
            echo "Mailer Error: " . $mail->ErrorInfo;
        }
    } else {
        echo "There was an error!";
    }
?>


我们非常感谢您的帮助。预先感谢。

1 个答案:

答案 0 :(得分:0)

您不是真的在这里尝试。您正在制作XHR,但是甚至没有尝试以适用于此格式的格式返回结果,也没有返回将触发错误处理程序的错误代码。首先,您需要设置正确的内容类型:

header('Content-type: application/json');

然后适当地处理错误或有效响应,以JSON格式给出结果:

    } catch (Exception $e) {
        //Some other code may be better, but anything other than 2xx will do for jQuery
        http_response_code(400);
        echo json_encode(['status' => false, 'errormessage' => $e->errorMessage(), 'errorinfo' => $mail->Errorinfo]);
        exit;
    }
    echo json_encode(['status' => true]);
    exit;

请注意,如果您对isset($_POST['submit'])的检查失败,则您什么都不要说(您当前正在显示错误),这就是他们第一次加载页面时发生的情况。