简体   繁体   English

Ajax联系表格错误

[英]Ajax Contact Form Error

My mail is not being sent by the code below. 我的邮件没有通过以下代码发送。

It shows a success message, but it's not being delivered to my gmail account. 它显示一条成功消息,但未发送到我的Gmail帐户。 Also, I have replaced mymail@email.com with my gmail id, but it is still not working. 另外,我已经用我的gmail ID替换了mymail@email.com ,但仍然无法正常工作。

HTML: 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 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]);

contact-form.php contact-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);

}
?>

Your code will always give you response success... 您的代码将始终为您提供成功的响应...

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

Please use it as 请用作

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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM