Reputation: 377
I want to send a form on button click with fetch API to index.php where i validate the form. If there were no errors in the form I want to send an email with PHPMailer to the client. 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:
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
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 = "[email protected]"; //paste one generated by Mailtrap
$mail->Password = 'mypasswd';
$mail->SMTPSecure = 'tls'; // secure transfer enabled REQUIRED for GMail
$mail->Port = 587;
$mail->addAddress("[email protected]", 'First Last');
$mail->addReplyTo('[email protected]', 'First Last');
$mail->setFrom('[email protected]', '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.
Upvotes: 0
Views: 975
Reputation: 37810
First of all, you are importing both versions 5 and 6 of PHPMailer! That's not going to go well; go with 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.
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);
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. 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.
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. 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.
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.
Upvotes: 2