Ajax联系表单错误

时间:2016-06-18 06:59:52

标签: javascript php jquery ajax email

我的邮件未通过以下代码发送。

它显示成功消息,但未将其发送到我的Gmail帐户。此外,我已使用我的Gmail帐号替换mymail@email.com,但它仍无效。

HTML:

<form id="contactForm" method="post" class="form-horizontal" action="php/contact-form.php">
    <div class="col-md-10 col-sm-12 col-xs-12 col-md-offset-1" style="padding-bottom: 20px;">
        <input type="text" class="form-control" name="name" id="name" value="" placeholder="Name">
    </div>
    <div class="col-md-10 col-sm-12 col-xs-12 col-md-offset-1" style="padding-bottom: 20px;">
        <input type="text" class="form-control" name="email" id="email" value="" placeholder="Email">
    </div>
    <div class="col-md-10 col-sm-12 col-xs-12 col-md-offset-1" style="padding-bottom: 20px;">
        <input type="text" class="form-control" name="subject" id="subject" value="" placeholder="Subject">
    </div>
    <div class="col-md-10 col-sm-12 col-xs-12 col-md-offset-1" style="padding-bottom: 20px;">
        <textarea class="form-control" name="message" rows="8" id="message" placeholder="Message"></textarea>
    </div>
    <div class="col-md-10 col-sm-12 col-xs-12 col-md-offset-1" style="padding-bottom: 20px;">
        <input type="submit" class="btn btn-primary" value="Submit">
    </div>
    <div class="col-md-10 col-sm-12 col-xs-12 col-md-offset-1">
    <div class="alert alert-success hidden" id="contactSuccess">
            <strong>Success!</strong> Your message has been sent to us.
        </div>
        </div>
        <div class="col-md-10 col-sm-12 col-xs-12 col-md-offset-1">
        <div class="alert alert-danger hidden" id="contactError">
            <strong>Error!</strong> There was an error sending your message.
        </div>
    </div>
</form>

view.contact.js

(function($) {

    'use strict';

    /*
    Contact Form: Basic
    */
    $('#contactForm:not([data-type=advanced])').validate({
        submitHandler: function(form) {

            var $form = $(form),
                $messageSuccess = $('#contactSuccess'),
                $messageError = $('#contactError'),
                $submitButton = $(this.submitButton);

            $submitButton.button('loading');

            // Ajax Submit
            $.ajax({
                type: 'POST',
                url: $form.attr('action'),
                data: {
                    name: $form.find('#name').val(),
                    email: $form.find('#email').val(),
                    subject: $form.find('#subject').val(),
                    message: $form.find('#message').val()
                },
                dataType: 'json',
                complete: function(data) {

                    if (typeof data.responseJSON === 'object') {
                        if (data.responseJSON.response == 'success') {

                            $messageSuccess.removeClass('hidden');
                            $messageError.addClass('hidden');

                            // Reset Form
                            $form.find('.form-control')
                                .val('')
                                .blur()
                                .parent()
                                .removeClass('has-success')
                                .removeClass('has-error')
                                .find('label.error')
                                .remove();

                            if (($messageSuccess.offset().top - 80) < $(window).scrollTop()) {
                                $('html, body').animate({
                                    scrollTop: $messageSuccess.offset().top - 80
                                }, 300);
                            }

                            $submitButton.button('reset');

                            return;

                        }
                    }

                    $messageError.removeClass('hidden');
                    $messageSuccess.addClass('hidden');

                    if (($messageError.offset().top - 80) < $(window).scrollTop()) {
                        $('html, body').animate({
                            scrollTop: $messageError.offset().top - 80
                        }, 300);
                    }

                    $form.find('.has-success')
                        .removeClass('has-success');

                    $submitButton.button('reset');

                }
            });
        }
    });

    /*
    Contact Form: Advanced
    */
    $('#contactFormAdvanced, #contactForm[data-type=advanced]').validate({
        onkeyup: false,
        onclick: false,
        onfocusout: false,
        rules: {
            'captcha': {
                captcha: true
            },
            'checkboxes[]': {
                required: true
            },
            'radios': {
                required: true
            }
        },
        errorPlacement: function(error, element) {
            if (element.attr('type') == 'radio' || element.attr('type') == 'checkbox') {
                error.appendTo(element.parent().parent());
            } else {
                error.insertAfter(element);
            }
        }
    });

}).apply(this, [jQuery]);

接触form.php的

<?php

session_cache_limiter('nocache');
header('Expires: ' . gmdate('r', 0));

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

// Step 1 - Enter your email address below.
$to = 'myemail@email.com';

// Step 2 - Enable if the server requires SMTP authentication. (true/false)
$enablePHPMailer = false;

$subject = $_POST['subject'];

if(isset($_POST['email'])) {

    $name = $_POST['name'];
    $email = $_POST['email'];

    $fields = array(
        0 => array(
            'text' => 'Name',
            'val' => $_POST['name']
        ),
        1 => array(
            'text' => 'Email address',
            'val' => $_POST['email']
        ),
        2 => array(
            'text' => 'Message',
            'val' => $_POST['message']
        )
    );

    $message = "";

    foreach($fields as $field) {
        $message .= $field['text'].": " . htmlspecialchars($field['val'], ENT_QUOTES) . "<br>\n";
    }

    // Simple Mail
    if(!$enablePHPMailer) {

        $headers = '';
        $headers .= 'From: ' . $name . ' <' . $email . '>' . "\r\n";
        $headers .= "Reply-To: " .  $email . "\r\n";
        $headers .= "MIME-Version: 1.0\r\n";
        $headers .= "Content-Type: text/html; charset=UTF-8\r\n";

        if (mail($to, $subject, $message, $headers)){
            $arrResult = array ('response'=>'success');
        } else{
            $arrResult = array ('response'=>'error');
        }

    // PHP Mailer Library - Docs: https://github.com/PHPMailer/PHPMailer
    } else {

        include("php-mailer/PHPMailerAutoload.php");

        $mail = new PHPMailer;

        $mail->IsSMTP();                                      // Set mailer to use SMTP
        $mail->SMTPDebug = 0;                                 // Debug Mode

        // Step 3 - If you don't receive the email, try to configure the parameters below:

        //$mail->Host = 'mail.yourserver.com';                // Specify main and backup server
        //$mail->SMTPAuth = true;                             // Enable SMTP authentication
        //$mail->Username = 'username';                       // SMTP username
        //$mail->Password = 'secret';                         // SMTP password
        //$mail->SMTPSecure = 'tls';                          // Enable encryption, 'ssl' also accepted

        $mail->From = $email;
        $mail->FromName = $_POST['name'];
        $mail->AddAddress($to);                               // Add a recipient
        $mail->AddReplyTo($email, $name);

        $mail->IsHTML(true);                                  // Set email format to HTML

        $mail->CharSet = 'UTF-8';

        $mail->Subject = $subject;
        $mail->Body    = $message;

        if(!$mail->Send()) {
           $arrResult = array ('response'=>'error');
        }

        $arrResult = array ('response'=>'success');

    }

    echo json_encode($arrResult);

} else {

    $arrResult = array ('response'=>'error');
    echo json_encode($arrResult);

}
?>

1 个答案:

答案 0 :(得分:0)

您的代码将始终为您提供响应成功...

if(!$mail->Send()) 
{
  $arrResult = array ('response'=>'error');
}
$arrResult = array ('response'=>'success');

请将其用作

if(!$mail->Send()) 
{
  $arrResult = array ('response'=>'error');
}
else
{
  $arrResult = array ('response'=>'success');
}