打印PHPMailer给出的错误或成功消息

时间:2018-06-27 13:15:56

标签: javascript ajax phpmailer contact-form

我有一个服务器端验证联系表,该表使用PHPMailer实际发送电子邮件。我有一个JavaScript,它仅通过AJAX / JSON接收带有错误消息的信息,并打印这些错误消息。

如果从PHPMailer收到消息,我希望javascript打印一条错误消息,或者隐藏联系表单并打印成功消息,但是我没有正确得到它。

这是我的Javascript尝试:

empty string

我使用PHPMailer的php脚本:

// Start
$(document).ready(function() {

    // process the form
    $('form').submit(function(event) {

        $('.form-group').removeClass('has-error'); // remove the error class
        $('.help-block').remove(); // remove the error text

        // get the form data
        // there are many ways to get this data using jQuery (you can use the class or id also)
        var formData = {
            'firstName'                 : $('input[name=firstName]').val(),
            'lastName'              : $('input[name=lastName]').val(),
            'companyName'               : $('input[name=companyName]').val(),
            'companyAddress'                : $('input[name=companyAddress]').val(),
            'city'              : $('input[name=city]').val(),
            'state'                 : $('input[name=state]').val(),
            'emailAddress'          : $('input[name=emailAddress]').val(),
            'comment'   : $('input[name=comment]').val(),
        };

        // process the form
        $.ajax({
            type        : 'POST', // define the type of HTTP verb we want to use (POST for our form)
            url         : 'formMaster.php', // the url where we want to POST
            data        : formData, // our data object
            dataType    : 'json', // what type of data do we expect back from the server
            encode      : true
            success: function(response) {
                if(response.status){
                    /* success */
                    $('button[name="submit"]').hide();
                    $('.error').hide()
                    $('.success').html(response.message).fadeIn(1000);
                }else{
                    /* error occurred show to user */
                    $('.success').hide();
                    $('button[name="submit"]').show();
                    $('.error').html(response.message).fadeIn(1000);
                }
            }
        })
            // using the done promise callback
            .done(function(data) {

                // log data to the console so we can see
                console.log(data);

                // here we will handle errors and validation messages
                if ( ! data.success) {

                    // handle errors for name ---------------
                    if (data.errors.firstName) {
                        $('#firstName-group').addClass('has-error'); // add the error class to show red input
                        $('#firstName-group').append('<div class="help-block">' + data.errors.firstName + '</div>'); // add the actual error message under our input
                    }

                    // handle errors for name ---------------
                    if (data.errors.lastName) {
                        $('#lastName-group').addClass('has-error'); // add the error class to show red input
                        $('#lastName-group').append('<div class="help-block">' + data.errors.lastName + '</div>'); // add the actual error message under our input
                    }

                    // handle errors for name ---------------
                    if (data.errors.companyName) {
                        $('#companyName-group').addClass('has-error'); // add the error class to show red input
                        $('#companyName-group').append('<div class="help-block">' + data.errors.companyName + '</div>'); // add the actual error message under our input
                    }

                    // handle errors for Company Address ---------------
                    if (data.errors.companyAddress) {
                        $('#companyAddress-group').addClass('has-error'); // add the error class to show red input
                        $('#companyAddress-group').append('<div class="help-block">' + data.errors.companyAddress + '</div>'); // add the actual error message under our input
                    }

                    // handle errors for Company Address ---------------
                    if (data.errors.city) {
                        $('#city-group').addClass('has-error'); // add the error class to show red input
                        $('#city-group').append('<div class="help-block">' + data.errors.city + '</div>'); // add the actual error message under our input
                    }

                    // handle errors for Company Address ---------------
                    if (data.errors.state) {
                        $('#state-group').addClass('has-error'); // add the error class to show red input
                        $('#state-group').append('<div class="help-block">' + data.errors.state + '</div>'); // add the actual error message under our input
                    }

                    // handle errors for Email Address ---------------
                    if (data.errors.emailAddress) {
                        $('#emailAddress-group').addClass('has-error'); // add the error class to show red input
                        $('#emailAddress-group').append('<div class="help-block">' + data.errors.emailAddress + '</div>'); // add the actual error message under our input
                    }

                    // handle errors for superhero alias ---------------
                    if (data.errors.comment) {
                        $('#comment-group').addClass('has-error'); // add the error class to show red input
                        $('#comment-group').append('<div class="help-block">' + data.errors.comment + '</div>'); // add the actual error message under our input
                    }

                    // handle errors for recaptcha ---------------
                    if (data.errors.recaptcha) {
                        $('#recaptcha-group').addClass('has-error'); // add the error class to show red input
                        $('#recaptcha-group').append('<div class="help-block">' + data.errors.recaptcha + '</div>'); // add the actual error message under our input
                    }

                } else {

                    // ALL GOOD! just show the success message!
                    $('form').append('<div class="alert alert-success">' + data.message + '</div>');

                    // usually after form submission, you'll want to redirect
                    // window.location = '/thank-you'; // redirect a user to another page

                }
            })

            // using the fail promise callback
            .fail(function(data) {

                // show any errors
                // best to remove for production
                console.log(data);
            });

        // stop the form from submitting the normal way and refreshing the page
        event.preventDefault();
    });

});

尝试#2:

<?php

include "recaptcha.php";
include 'email.php';
use PHPMailer\PHPMailer\PHPMailer;
use PHPMailer\PHPMailer\Exception;

require 'Exception.php';
require 'PHPMailer.php';
require 'SMTP.php';

$errors         = array();      // array to hold validation errors
$data           = array();         // array to pass back data

// validate the variables ======================================================
    // if any of these variables don't exist, add an error to our $errors array

    if (empty($_POST['firstName']))
        $errors['firstName'] = 'First Name is required.';

    if (empty($_POST['lastName']))
        $errors['lastName'] = 'Last Name is required.';

    if (empty($_POST['companyName']))
        $errors['companyName'] = 'Company Name is required.';

    if (empty($_POST['companyAddress']))
        $errors['companyAddress'] = 'Company Address is required.';

    if (empty($_POST['city']))
        $errors['city'] = 'City is required.';

    if (empty($_POST['state']))
        $errors['state'] = 'State is required.';

    if (empty($_POST['emailAddress']))
        $errors['emailAddress'] = 'Email Address is required.';

    if (empty($_POST['comment']))
        $errors['comment'] = 'Comment is required.';

    if (empty($_POST['g-recaptcha-response']))
        $errors['recaptcha'] = 'Captcha is required.';


// return a response ===========================================================

    // Check ReCaptcha Validation

    if(!validateRecaptcha($secret, $_POST['g-recaptcha-response'], $_SERVER["REMOTE_ADDR"]))
    {
        $errors['recaptcha'] = 'Captcha is required.';
    }

    if ( ! empty($errors)) {

        // if there are items in our errors array, return those errors
        $data['success'] = false;
        $data['errors']  = $errors;
    } else {

        // if there are no errors process our form, then return a message

        // DO ALL YOUR FORM PROCESSING HERE
        // THIS CAN BE WHATEVER YOU WANT TO DO (LOGIN, SAVE, UPDATE, WHATEVER)

        // show a message of success and provide a true success variable
        $data['success'] = true;
        $data['message'] = 'Success!';
    }

    // return all our data to an AJAX call
    echo json_encode($data);

//Begin of send email
$mail = new PHPMailer;

//Enable SMTP debugging.
$mail->SMTPDebug = 3;
//Set PHPMailer to use SMTP.
$mail->isSMTP();
//Set SMTP host name
$mail->Host = "smtp.server.com";
//Set this to true if SMTP host requires authentication to send email
$mail->SMTPAuth = true;
//Provide username and password
$mail->Username = "user@server.com";
$mail->Password = "super_secret_password";
//If SMTP requires TLS encryption then set it
$mail->SMTPSecure = "tls";
//Set TCP port to connect to
$mail->Port = 587;

$mail->From = $emailAddress;

$mail->addAddress("name@server.com", "Recepient Name");

$mail->isHTML(true);

$mail->Subject = "Subject Text";
$mail->Body = $emailBody;

$response = array();
if(!$mail->send()) {
  $response = array('message'=>"Mailer Error: " . $mail->ErrorInfo, 'status'=> 0);
} else {
  $response = array('message'=>"Message has been sent successfully", 'status'=> 1);
}

/* send content type header */
header('Content-Type: application/json');

/* send response as json */
echo json_encode($response);
?>

2 个答案:

答案 0 :(得分:0)

您的ajax调用语法似乎只有一个成功处理程序,没有错误处理程序,而且在encode: true之后您丢失了逗号

encode      : true,
success: function(response) {
    if(response.status){
        /* success */
        $('button[name="submit"]').hide();
        $('.error').hide()
        $('.success').html(response.message).fadeIn(1000);
    }else{
        /* error occurred show to user */
        $('.success').hide();
        $('button[name="submit"]').show();
        $('.error').html(response.message).fadeIn(1000);
    }
},
error: function(response){
    console.log(response);
}

也许这会有所帮助?

答案 1 :(得分:0)

您的PHP结构有些混乱。您将发送两次JSON响应(包括在发送内容类型标头之前),因此很难获得JS可以处理的有效响应。

echo json_encode($data);
...
header('Content-Type: application/json');
...
echo json_encode($response);

保存您的回复直到最后,然后将其全部发送出去。

您还需要先设置$data['success'] = true;,然后再确认发送成功,然后再等待{}。