Ajax 没有将表单数据发送到我的 PHP 文件以发送邮件

Ajax doesn't send form data to my PHP file to send mail

我正在尝试使用 Ajax 和 PHPMailer 创建联系表。

我已经设法用我的 html 表格和我的 php 文件发送了一封邮件;但是,我想使用 Ajax 来防止页面重新加载并显示一个弹出窗口告诉用户邮件是否已发送。 当我尝试提交表单时,没有任何反应,当我删除 JQuery 函数中的事件参数时,页面永远加载。

我尝试在我的 js 文件中不包含 Ajax 的情况下显示弹出窗口并且它工作正常,所以我假设 JQuery 库已正确导入,问题是 Ajax 没有' 将我的数据发送到我的 php 文件。

我的HTML表格:

<form id="contact" method="post" action="traitement-formulaire.php">
                <div class="form-group">
                  <div class="form-row">
                    <div class="col">
                      <label for="formGroupExampleInput">Nom</label>
                      <input type="text" name="nom" class="form-control" placeholder="Votre nom" id="nom">
                    </div>
                    <div class="col">
                      <label for="formGroupExampleInput2">Prénom</label>
                      <input type="text" name="prenom" class="form-control" placeholder="Votre prénom" id="prenom">
                    </div>
                  </div>
                </div>
                <div class="form-group">
                  <label for="formGroupExampleInput2">Adresse mail</label>
                  <input type="text" name="mail" class="form-control" id=" mail formGroupExampleInput2" placeholder="ex.: exemple@gmail.com">
                </div>
                <div class="form-group">
                  <label for="formGroupExampleInput2">Sujet</label>
                  <input type="text" name="sujet" class="form-control" id=" sujet formGroupExampleInput2" placeholder="Objet de votre demande">
                </div>
                <div class="form-group">
                  <label for="formGroupExampleInput2">Votre message</label>
                  <textarea type="text" name="message" class="form-control" id=" message formGroupExampleInput2" placeholder="Détaillez votre demande ici..."></textarea>
                </div>
                <div class="form-group form-actions">
                  <button class="submit-form btn btn-primary btn-block btn-lg" name="submit" type="submit" value="submit">Envoyer</button>
                </div>
              </form>

我的 JQuery 文件:

$(document).ready(function(){
$('#contact').submit(function(e){
    e.preventDefault();
    $.ajax({
        dataType: 'JSON',
        url: 'traitement-formulaire.php',
        type: 'POST',
        data: $('#contact').serialize(),
        success: function(data) {
            $('.alert-success').css('display', 'block');
            setTimeout(function(){
                $('.alert-success').css('display' , 'none');
                $('#nom').val("");
                $('#prenom').val("");
                $('#mail').val("");
                $('sujet').val("");
                $('#message').val("")
            }, 3000);
        },
        error: function(data) {
            $('.alert-danger').css('display', 'block');
            setTimeout(function(){
                $('.alert-danger').css('display' , 'none');
                $('#nom').val("");
                $('#prenom').val("");
                $('#mail').val("");
                $('#sujet').val("");
                $('#message').val("")
            }, 3000);
        }
    });
});

});

我的 PHP 文件:

<?php
use PHPMailer\PHPMailer\PHPMailer;
use PHPMailer\PHPMailer\Exception;

require 'PHPMailer/src/Exception.php';
require 'PHPMailer/src/PHPMailer.php';
require 'PHPMailer/src/SMTP.php';

$nom = trim($_POST['nom']);
$prenom = trim($_POST['prenom']);
$mail = trim($_POST['mail']);
$sujet = trim($_POST['sujet']);
$message = trim($_POST['message']);

// Instantiation and passing `true` enables exceptions
$mail = new PHPMailer(true);

try {
    //Server settings
    $mail->SMTPDebug = 0;                                       // Enable verbose debug output
    $mail->isSMTP();                                            // Set mailer to use SMTP
    $mail->Host       = 'ns0.ovh.net';  // Specify main and backup SMTP servers
    $mail->SMTPAuth   = true;                                   // Enable SMTP authentication
    $mail->Username   = 'postmaster@sp-neo.com';                     // SMTP username
    $mail->Password   = '*************';                               // SMTP password
    $mail->SMTPSecure = 'ssl';                                  // Enable TLS encryption, `ssl` also accepted
    $mail->Port       = 465;                                    // TCP port to connect to

    //Recipients
    $mail->setFrom($mail, $nom);
    $mail->addAddress('contact@sp-neo.com');     // 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 = $sujet;
    $mail->Body    = $message;
    //$mail->AltBody = 'This is the body in plain text for non-HTML mail clients';

    $mail->send();
    header( 'Location: index.html' );
} catch (Exception $e) {
    echo "Message could not be sent. Mailer Error: {$mail->ErrorInfo}";
}

?>

感谢您的帮助!

编辑:

HTML 弹出窗口代码:

  <!--Alert-->
  <div class="alert alert-success" role="alert" id="popup-success">
      Votre message a bien été envoyé.
  </div>
  <div class="alert alert-danger" role="alert" id="popup-error">
      Erreur: Votre message n'a pas pu être envoyé.
  </div>
  <!--Alert-->

CSS 弹出窗口代码:

#popup-success{
display: none;
}
#popup-error{
    display: none;
}

添加一个答案,以免遇到相同问题的人浏览评论。

你的第一个问题是你要么使用 slim jQuery,要么在你的脚本之后加载 jQuery。

那么你的 PHPMailer 文件的路径是错误的。

最后,您从表单中读取邮件并将其添加到 $mail 变量

$mail = trim($_POST['mail']);

但随后您在同一个变量上初始化了 PHPMailer 对象

$mail = new PHPMailer(true);

改变

$mail = trim($_POST['mail']);

类似于

$sender = trim($_POST['mail']);

并更改此行

$mail->setFrom($mail, $nom);

$mail->setFrom($sender, $nom);

你终于有了 dataType: 'JSON', 但你的脚本没有响应 JSON

您应该将其更改为 dataType: 'text', 并在 $mail->send();

之后添加 echo "mail sent";

同时删除 header( 'Location: index.html' );,因为它没有任何作用。