带有 PHPMailer 的 jQuery AJAX + PHP 表单

Posted

技术标签:

【中文标题】带有 PHPMailer 的 jQuery AJAX + PHP 表单【英文标题】:jQuery AJAX + PHP form with PHPMailer 【发布时间】:2021-08-17 23:48:25 【问题描述】:

有人可以帮帮我吗?我在发送 AJAX 请求并在后端 php 脚本上验证它时遇到问题。

这是我的代码: PHP Handler(smtp 设置 100% 有效且经过测试):

<?php

use PHPMailer\PHPMailer\PHPMailer;
use PHPMailer\PHPMailer\Exception;

require_once('PHPMailer/Exception.php');
require_once('PHPMailer/PHPMailer.php');
require_once('PHPMailer/SMTP.php');

if(empty($_SERVER['HTTP_X_REQUESTED_WITH']) || $_SERVER['HTTP_X_REQUESTED_WITH'] != 'XMLHttpRequest') 
    exit();

if ($_SERVER['REQUESTED_METHOD'] != 'POST') 
    exit();


if($_SERVER['REQUEST_METHOD'] == 'POST' && isset($_POST['name']) && isset($_POST['message']))  

    function secure_input($data)
    
        $data = trim($data);
        $data = filter_var($data, FILTER_SANITIZE_STRING);
        $data = str_replace(array("\r", "\n"), array(" ", " "), $data);
        $data = stripslashes($data);
        $data = htmlspecialchars($data);
        return $data;
    

    $name = secure_input($_POST["name"]);
    $message = secure_input($_POST["message"]);

    if(!empty($_FILES['attachment']))
    
        $file_name = $_FILES['attachment']['name'];
        $file_tmp_name = $_FILES['attachment']['tmp_name'];
        $file_size = $_FILES['attachment']['size'];
        if($file_size < '2048000')
        
            $file_path = move_uploaded_file($file_tmp_name, $file_name);
        else
            print json_encode(['error'=>1,'msg'=>"Oops! File upload size exceeded...", $file_size]);
            exit;
        
    

    $mail = new PHPMailer(true);
    $mail->CharSet = 'UTF-8';
    $mail->IsSMTP();
    $mail->SMTPDebug = 4;
    $mail->SMTPAuth = TRUE;
    $mail->SMTPSecure = "ssl";
    $mail->Port     = 465;
    $mail->Username = "smtp.user";
    $mail->Password = "smt.pass";
    $mail->Host     = "smtp.domain.com";
    $mail->Mailer   = "smtp";
    $mail->SetFrom("email@domain.com");
    $mail->AddReplyTo($_POST["email"]);
    $mail->AddAddress("my@gmail.com");
    $mail->IsHTML(true);
    $mail->Subject = ("MyForm Subject");
    $mail->Body = "
    <h1>Hello dear admin!</h1>
    <p>I am your personal mail delivery robot.</p>
    <b>I have something new for you submitted from the form myForm</b>
    Message: <p>$message</p>
    ";
    $mail->WordWrap   = 80;
    $mail->MsgHTML($_POST["message"]);

    if (is_array($_FILES['attachment'])) 
        $mail->AddAttachment($file_tmp_name, $file_name);
    
        if (!$mail->send()) 
            $message = 'Error';
        else
            $message = 'Email sent successfully';
        
    
    $response = ['message' => $message];
    header('Content-type: application/json');
    echo json_encode($response);

jQuery 代码;

$(document).ready(function() 
            $("#submitMyForm").click(function(e) 
                e.preventDefault();
                jQuery.validator.addMethod("validDate", function(value, element) 
                    return this.optional(element) || moment(value, "MM/DD/YY").isValid();
                , "Please enter a valid date in the format MM/DD/YY");
                jQuery.validator.addMethod("phoneTest", function(value, element) 
                    if (/\(?([0-9]3)\)?([ .-]?)([0-9]3)\2([0-9]4)/.test(value)) 
                        return true;
                     else 
                        return false;
                    ;
                , "Invalid phone number");
                $("#myForm").validate(
                    rules: 
                        scheduleAudience: 
                            required: true,
                        ,
                        date: 
                            required: true,
                            validDate: true
                        ,
                        time: 
                            required: true
                        ,
                        fName: 
                            required: true,
                            lettersonly: true,
                            minlength: 2,
                            maxlength: 30
                        ,
                        lName: 
                            required: true,
                            lettersonly: true,
                            minlength: 2,
                            maxlength: 30
                        ,
                        email: 
                            required: true,
                            email: true
                        ,
                        phone: 
                            required: true,
                            phoneTest: true
                        ,
                        preferences: 
                            required: true
                        ,
                        message: 
                            required: true,
                            minlength: 20,
                            maxlength: 500
                        ,
                        messages: 
                            fName: 
                                minlength: "Please, provide information with minimum - 2 Characters",
                                maxlength: "Please, provide information with maximum - 30 Characters"
                            ,
                            lName: 
                                minlength: "Please, provide information with minimum - 2 Characters",
                                maxlength: "Please, provide information with maximum - 30 Characters"
                            ,
                            message: 
                                minlength: "Please, provide information with minimum - 20 Characters",
                                maxlength: "Please, provide information with maximum - 500 Characters"
                            
                        ,
                    
                );

                if ((!$('#myForm').valid())) 
                    return false;
                
                if (($('#myForm').valid())) 
                    var formData = $("#myForm").serialize();
                    var URL = $("#myForm").attr("action");
                    $.ajax(
                        url: URL,
                        type: "POST",
                        data: formData,
                        cache: false,
                        processData: false,
                        contentType: false,
                        success: function(data) 
                            alert(JSON.stringify(response));
                            if (response.status == 1) 
                                swal(
                                    title: "Good job!",
                                    text: "We will get in touch with you soon",
                                    icon: "success",
                                );
                            
                        ,
                        error: function(response) 
                            alert(JSON.stringify(response));
                        
                    );
                
            )
            $("#attachment").change(function() 
                var file = this.files[0];
                var fileType = file.type;
                var match = ['image/jpeg', 'image/jpg', 'image/png'];
                if (!((fileType == match[0]) || (fileType == match[1]) || (fileType == match[2]))) 
                    swal(
                        title: "Invalid file format",
                        text: "Sorry, only JPEG, JPG and PNG files are allowed to upload!",
                        icon: "error",
                    );
                    $("#attachment").val('');
                    return false;
                
            );
        );

HTML 表单

<form class="contact100-form validate-form" id="myForm" name="myForm" action="URL_TO_PHPSCRIPT" method="post">

现在我得到一个错误: Uncaught ReferenceError: response is not defined without dataType: "json",我认为这是因为我在成功方法中使用了警报中的响应,我需要将其替换为数据? 使用 dataType: "json" 我得到一个错误:"readyState":4,"responseText":"","status":200,"statusText":"parsererror"

在这种情况下验证表单的正确方法是什么?并强制使用phpmailer

为方便起见,我通过删除其他变量的声明来减少代码长度。

【问题讨论】:

你使用success: function(data) ,在你使用secure_input破坏输入之前做一些基本的isset检查 谢谢!我现在收到这个 "readyState":4,"responseText":"","status":200,"statusText":"parsererror" 的错误 我添加了 isset 检查,但没有帮助 ` if($_SERVER['REQUEST_METHOD'] == 'POST' && isset($_POST['name']) && isset($_POST[ '消息'])) ` 【参考方案1】:

总的来说,我尝试了很多东西,得出的结论是 PHP 处理程序中存在错误。 在我真正理解问题所在之前,我已经伤透了脑筋。

【讨论】:

以上是关于带有 PHPMailer 的 jQuery AJAX + PHP 表单的主要内容,如果未能解决你的问题,请参考以下文章

PHPMailer 不发送带有附加 zip 文件的邮件

带有 yandex 邮件的 phpmailer 类

带有 mandrill smtp 的 PHPMailer 给出连接错误

使用phpmailer通过带有图像的html文件发送电子邮件

PHPMailer 发送电子邮件并返回带有回显的空白页面

当我们使用 phpMailer 发送带有动态内容的邮件时,如何在电子邮件正文中显示多个内联图像