带有 AJAX 的 PHP 邮件不会从服务器返回验证错误


PHP mail with AJAX won't return validation errors form server

我正在尝试发送一封带有PHP和AJAX的电子邮件,它终于可以工作了,但它不会显示从服务器返回的验证错误。我想我在迭代这些数据时做错了什么,或者只是不理解将 PHP 和 jQuery 与 JSON 连接起来。

服务器上的 PHP 邮件脚本:

$to = "mymail@gmail.com";
if (isset($_POST['name'], $_POST['mail'], $_POST['text'])) {
    if (empty($_POST['name'])) {
        $errors[] = "Molimo unesite Vaše ime";
    } else {
        $contact_name = htmlentities($_POST['name']);
    }
if (empty($_POST['mail'])) {
    $errors[] = "Molimo unesite Vašu email adresu.";
} else if (strlen($_POST['mail']) > 60) {
    $errors[] = "Vaša email adresa je predugačka.";
} else if (filter_var($_POST['mail'], FILTER_VALIDATE_EMAIL) === false ) {
    $errors[] = "Unesite validnu email adresu.";
} else {
    $contact_mail = "<" . htmlentities($_POST['mail']) . ">";
}
    if (empty($_POST['text'])) {
        $errors[] = "Molimo unesite poruku.";
    } else {
        $contact_text = htmlentities($_POST['text']);
    }
}
if (empty($errors) === true) {
    if(isset($contact_text, $contact_name, $contact_mail)) {
        $subject = "Mail from " . $contact_name ." via www.mysite.com";
        $headers = "From: " . $contact_mail;
        $sent = mail($to, $subject, $contact_text, $headers);
        if ($sent) {
            die("true");
        } else {
            return json_encode($errors);
        }
    }
}

相关j查询:

var mailBroker = {
    send : function() { //initial validation and sending to server
        var contact_name = $('input[name="contact-name"]').val();
        var contact_mail = $('input[name="contact-mail"]').val();
        var contact_text = $('textarea[name="contact-text"]').val();
        var status = ""; //send success status
        if (contact_name === "" || contact_mail === "" || contact_text === "") {
            //form not complete
        } else {
            $.post("includes/mail.php", { //post form data to server
                name : contact_name,
                mail : contact_mail,
                text : contact_text
            }, function(data) {
                var response = data;
                if (data === "true") { //succesful
                    mailBroker.setStatus('Poruka poslata.');
                } else {
                    var parsedData = $.parseJSON(data);
                    $.each(parsedData, function() {
                        var that = $(this);
                        setStatus(that);
                    });
                }
            });
        }
    },
    setStatus : function(status) {
        $('textarea[name="contact-text"]').after('<span>' + status + '</span>');
    }
}

和内部$(document).ready()

$('#contact-us form').submit(function(event) {
    event.preventDefault();
    mailBroker.send();
    $(this).trigger('reset');
});

有人可以指出我做错了什么吗?

当然,我知道我可以在客户端这样做,但这是不好的做法。因此,我暂时省略了该部分,并假设必填表单字段的数据无效或没有数据通过。

答案形式更容易解释这一点。代码中的逻辑永远不会让脚本有机会将错误输出到 AJAX。您需要更改逻辑,以便更改逻辑。 即。

if (empty($errors) === true) {
    if(isset($contact_text, $contact_name, $contact_mail)) {
        $subject = "Mail from " . $contact_name ." via www.mysite.com";
        $headers = "From: " . $contact_mail;
        $sent = mail($to, $subject, $contact_text, $headers);
        if ($sent) {
            die("true");
        } else {
            die("false"); // with json_encode here, $errors will always be empty
        }
    }
} else {
    die(json_encode($errors)); //$errors wasn't empty, this is where you need to hand it back to the JS.
}

这就是为什么Firebug或其他工具会有所帮助的原因。你会看到你想要提供给JS的信息不存在 - 这样你就知道查看PHP(服务器端),因为它没有按预期输出。如果是,您将签入JS代码以查看为什么它没有按预期处理它。

编辑:你的javascript不允许PHP在字段为空时

执行,但你想要PHP在字段为空时给出的反馈,所以你想把你的JS改成这样:

var mailBroker = {
    send : function() { //initial validation and sending to server
    var contact_name = $('input[name="contact-name"]').val();
    var contact_mail = $('input[name="contact-mail"]').val();
    var contact_text = $('textarea[name="contact-text"]').val();
    var status = ""; //send success status
    $.post("includes/mail.php", { //post form data to server
    name : contact_name,
    mail : contact_mail,
    text : contact_text
    }, function(data) {
    var response = data;
    if (data === "true") { //succesful
        mailBroker.setStatus('Poruka poslata.');
    } else {
        var parsedData = $.parseJSON(data);
        $.each(parsedData, function() {
        var that = $(this);
        setStatus(that);
        });
    }
    });
    },
    setStatus : function(status) {
    $('textarea[name="contact-text"]').after('<span>' + status + '</span>');
    }
}

对 Jon 的答案稍作修改,因为您仍然需要从返回的 JSON 中提取消息:

var mailBroker = {
    'send' : function() { //initial validation and sending to server
        var contact_name = $('input[name="contact-name"]').val();
        var contact_mail = $('input[name="contact-mail"]').val();
        var contact_text = $('textarea[name="contact-text"]').val();
        var status = ""; //send success status
        $.post("includes/mail.php", { //post form data to server
            name : contact_name,
            mail : contact_mail,
            text : contact_text
        }, function(data) {
            var response = data;
            if (data === "true") { //succesful
                mailBroker.setStatus('Poruka poslata.');
                $('#contact-us form').trigger('reset');
            } else { //validation failed
                var parsedData = $.parseJSON(data);
                var msg = '';
                $.each(parsedData, function() {
                    var that = $(this);
                    for (var i = 0; i < that.size(); i++) {
                        msg += that[i];
                    }
                    mailBroker.setStatus(msg); //msg used to be 'that'
                    msg = '';
                });
            }
        });
    },
    'setStatus' : function(status) {
        $('#validation-msgs').prepend('<p class="validation-msg">' + status + '</p>');
    }
}

本质上 - 您需要传递解析的数据来获取每条消息。问题是它们也存储为字符数组。因此,您还需要传递这些字符,并将这些字符附加到消息字符串中。

然后,应将这些消息附加到某个容器中以发出警告,以便它们按正确的顺序排列。如果不这样做,您将获得 [对象] 而不是消息文本。

希望这有帮助。

嗨,

我想你搞砸了你的第 3 行邮件脚本。 if (isset($_POST['name'], $_POST['mail'], $_POST['text'])) {因为您将为此使用比较运算符。

像下面这样。

if (isset($_POST['name'] && $_POST['mail'] && $_POST['text'])) {