未捕获的TypeError:无法读取未定义的属性“ firstName”

时间:2018-09-21 17:29:47

标签: javascript ajax

我得到了一个AJAX脚本,该脚本在服务器端执行验证,然后将错误传递给Javascript进行打印。

当我尝试提交空白表格时,不是打印错误,而是在控制台上抛出错误:

formMaster.js:41 Uncaught TypeError: Cannot read property 'firstName' of undefined
    at Object.<anonymous> (formMaster.js:41)
    at l (jquery.min.js:4)
    at Object.fireWith [as resolveWith] (jquery.min.js:4)
    at k (jquery.min.js:6)
    at XMLHttpRequest.<anonymous> (jquery.min.js:6)

但是我不确定我要去哪里错了。

这是我的Javascript:

// 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
        })
            // using the done promise callback
            .done(function(data) {

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

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

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

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

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

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

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

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

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

                    // handle errorsMSG for superhero alias ---------------
                    if (data.errorsMSG.comment) {
                        $('#comment-group').addClass('has-error'); // add the error class to show red input
                        $('#comment-group').append('<div class="help-block">' + data.errorsMSG.comment + '</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 errorsMSG
                // best to remove for production
                console.log(data);
            });

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

});

如果有人需要PHP脚本,则在这里:

<?php
//Show errors
ini_set('display_errors', 1);
ini_set('display_startup_errors', 1);
error_reporting(E_ALL);

//Load Required Components
require_once 'src/recaptcha_autoload.php';
use PHPMailer\PHPMailer\PHPMailer;
use PHPMailer\PHPMailer\Exception;
require 'src/Exception.php';
require 'src/PHPMailer.php';
require 'src/SMTP.php';

$errorsMSG = 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 $errorsMSG array
if (empty($_POST['firstName'])) $errorsMSG['firstName'] = 'First Name is required.';
if (empty($_POST['lastName'])) $errorsMSG['lastName'] = 'Last Name is required.';
if (empty($_POST['companyName'])) $errorsMSG['companyName'] = 'Company Name is required.';
if (empty($_POST['companyAddress'])) $errorsMSG['companyAddress'] = 'Company Address is required.';
if (empty($_POST['city'])) $errorsMSG['city'] = 'City is required.';
if (empty($_POST['state'])) $errorsMSG['state'] = 'State is required.';
if (empty($_POST['emailAddress'])) $errorsMSG['emailAddress'] = 'Email Address is required.';
if (empty($_POST['comment'])) $errorsMSG['comment'] = 'Comment is required.';
// return a response ===========================================================
// if there are any errors in our errors array, return a success boolean of false
if (!empty($errorsMSG)) {
    // if there are items in our errors array, return those errors
    $data['success'] = false;
    $data['errors'] = $errorsMSG;
} else {
    checkRecaptcha();
}
function checkReCaptcha() {
    $recaptcha = new \ReCaptcha\ReCaptcha($secret);
    $resp = $recaptcha->setExpectedHostname('recaptcha-demo.appspot.com')->setExpectedAction('homepage')->setScoreThreshold(0.5)->verify($gRecaptchaResponse, $remoteIp);
    if ($resp->isSuccess()) {
        // Verified!
        //PHP Mailer Function
        sendMail();
    } else {
        $errors = $resp->getErrorCodes();
        $errorsMSG = 'Captcha is required!';
    }
    //End of Google Recaptcha Function

}
function sendMail($email) {
    $mail = new PHPMailer(true); // Passing `true` enables exceptions
    try {
        //Server settings
        $mail->SMTPDebug = 2; // Enable verbose debug output
        $mail->isSMTP(); // Set mailer to use SMTP
        $mail->Host = 'smtp1.example.com;smtp2.example.com'; // Specify main and backup SMTP servers
        $mail->SMTPAuth = true; // Enable SMTP authentication
        $mail->Username = 'user@example.com'; // SMTP username
        $mail->Password = 'secret'; // SMTP password
        $mail->SMTPSecure = 'tls'; // Enable TLS encryption, `ssl` also accepted
        $mail->Port = 587; // TCP port to connect to
        //Recipients
        $mail->setFrom('from@example.com', 'Mailer');
        $mail->addAddress('joe@example.net', 'Joe User'); // Add a recipient
        $mail->addAddress('ellen@example.com'); // Name is optional
        $mail->addReplyTo('info@example.com', 'Information');
        $mail->addCC('cc@example.com');
        $mail->addBCC('bcc@example.com');
        //Attachments
        $mail->addAttachment('/var/tmp/file.tar.gz'); // Add attachments
        $mail->addAttachment('/tmp/image.jpg', 'new.jpg'); // Optional name
        //Content
        $mail->isHTML(true); // Set email format to HTML
        $mail->Subject = 'Here is the subject';
        $mail->Body = 'This is the HTML message body <b>in bold!</b>';
        $mail->AltBody = 'This is the body in plain text for non-HTML mail clients';
        $mail->send();
        $errorsMSG = 'Message successfully sent.';
    }
    catch(Exception $e) {
        $errorsMSG = 'There has been an issue sending your message.';
        $mail->ErrorInfo;
    }
    //End of sendMail Function

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

我想念什么?

0 个答案:

没有答案