简体   繁体   English

使用 FETCH 单击按钮提交表单并使用 PHPMailer 发送 email

[英]Submit form on button click with FETCH and send an email with PHPMailer

I want to send a form on button click with fetch API to index.php where i validate the form.我想在单击按钮时发送一个表单,并将 API 提取到 index.php 以验证表单。 If there were no errors in the form I want to send an email with PHPMailer to the client.如果表单中没有错误,我想将带有 PHPMailer 的 email 发送到客户端。 For some reason the client does not receive the e-mail.由于某种原因,客户端没有收到电子邮件。 I have searched for hours for an answer but I couldn't solve the problem.我已经搜索了几个小时的答案,但我无法解决问题。

Here is the javascript code:这是 javascript 代码:

 const form = document.querySelector("#myForm");
      form.addEventListener("submit", (e) => {
        e.preventDefault();
        const formData = new FormData(form);
        fetch("index.php", {
          method: 'post',
          body: formData
        }).then((resp) => resp.json())
        .then(function (text) {
          console.log(text); //Do something with the response, which is an array
          if(text !== undefined && text.length > 0) { //The array isn't empty
            //Show errors
            const formdiverror = document.querySelector(".col-100-form-error");
            const colform = document.querySelector(".col-100-form"); //showing error
            colform.style.display = "block";
            formdiverror.innerHTML = "";
            text.forEach(t => formdiverror.innerHTML += t + "</br>");
          } else {
            //array is empty, no errors
             const colform = document.querySelector(".col-100-form");
             if(colform !== null || colform !== undefined) colform.style.display = "none";
             alert("You succesfully bought the product!");
            //window.location.replace("index.html"); //if there was no error redirect to index.html
          }
        });
      })

The php: php:

<?php
use PHPMailer\PHPMailer\PHPMailer;
use PHPMailer\PHPMailer\SMTP;
require 'Exception.php';
require 'PHPMailer.php';
require 'SMTP.php';
require 'PHPMailerAutoload.php';
require "class.phpmailer.php";
require "class.smtp.php";


$errors = [];

if(isset($_POST["name"])) {
   
     /*I took out the validation to simplify the code*/
    if (!empty($errors)) {
        echo json_encode($errors);
    } else {
        echo json_encode([]);
        $mail = new PHPMailer();
        $mail->isSMTP();
        $mail->Host = 'smtp.gmail.com';
        $mail->SMTPAuth = true;
        $mail->Username = "mymail@gmail.com"; //paste one generated by Mailtrap
        $mail->Password = 'mypasswd'; 
        $mail->SMTPSecure = 'tls'; // secure transfer enabled REQUIRED for GMail
        $mail->Port = 587;
        $mail->addAddress("customer@gmail.com", 'First Last');
        $mail->addReplyTo('mymail@gmail.com', 'First Last');
        $mail->setFrom('mymail@gmail.com', 'John Doe');
        $mail->Subject = 'PHPMailer GMail SMTP test';
        $mail->isHTML(true);
        $mailContent = "<h1>Send HTML Email using SMTP in PHP</h1>
        <p>This is a test email I’m sending using SMTP mail server with PHPMailer.</p>";
         $mail->Body = $mailContent;
         $mail->send();
        //If I try this way it gives an errror: Unexpected token in JSON at position 
        /* if($mail->send()){
            echo ('Message has been sent');
        }else{
            echo ('Message could not be sent.');
            echo ('Mailer Error: ' . $mail->ErrorInfo);
        }*/
    }
} 
?>

I don't get any errors so I don't know where the problem is.我没有收到任何错误,所以我不知道问题出在哪里。 I have disabled the two way verification, and I gave access to less secure apps.我已禁用双向验证,并允许访问不太安全的应用程序。

First of all, you are importing both versions 5 and 6 of PHPMailer;首先,您要导入 PHPMailer 的 56 版本; That's not going to go well.这对 go 不好。 go with 6; go 6; Delete these lines and the files they point to: you don't need them:删除这些行和它们指向的文件:你不需要它们:

require 'PHPMailerAutoload.php';
require "class.phpmailer.php";
require "class.smtp.php";

If you're confused about how to import libraries in general, now would be a very good time to learn about composer .如果您对如何导入库感到困惑,那么现在是学习composer的好时机。

Oddly enough, when you comment out code that shows you where the error is, it no longer shows you when there's an error... that console.log(text);奇怪的是,当您注释掉向您显示错误所在的代码时,它不再向您显示出现错误时... console.log(text); line should show you what your browser sees too.行也应该向您显示您的浏览器看到的内容。

The best way to approach this is to debug one thing at a time.解决此问题的最佳方法是一次调试一件事。

First make sure that your form is actually delivering the data to your script in the format that it should be – given the JSON error (which is not from PHPMailer), it seems very likely that this is not the case, and that's probably the source of all your problems.首先确保您的表单实际上以应有的格式将数据传递给您的脚本 - 考虑到 JSON 错误(不是来自 PHPMailer),看起来很可能不是这种情况,这可能是源你所有的问题。 So add this near the top of your script:所以在你的脚本顶部附近添加这个:

var_dump($_REQUEST);

This will break your ajax request (because the output is not JSON), but you will be able to see the raw response in your browser's web inspector.这将破坏您的 ajax 请求(因为 output 不是 JSON),但您将能够在浏览器的 web 检查器中看到原始响应。

Once you've confirmed that it's in the correct format and contains all your expected form data, remove that var_dump line and move on to checking that you are accessing the properties within the JSON correctly.一旦您确认它的格式正确并包含所有预期的表单数据,请删除该var_dump行并继续检查您是否正确访问了 JSON 中的属性。 Again, you may find it best to show this in your browser's inspector.同样,您可能会发现最好在浏览器的检查器中显示此内容。 Once you're sure you're extracting all the bits of data you want in the right way, moving on to sending an email.一旦确定以正确的方式提取所需的所有数据位,就可以继续发送 email。

Given the very common problems with using gmail via SMTP, it's a good idea to test your email code with fixed values, separately from your ajax stuff – it's hard enough to debug by itself without other stuff getting in the way. Given the very common problems with using gmail via SMTP, it's a good idea to test your email code with fixed values, separately from your ajax stuff – it's hard enough to debug by itself without other stuff getting in the way.

Now you've got to the point where all the individual pieces work, join them back together and check each step as you do so.现在你已经到了所有单独的部分都可以工作的地步,将它们重新组合在一起,并在你这样做的时候检查每一步。

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

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