javascript - Submit form on button click with FETCH and send an email with PHPMailer
one text
Solution:
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.
Source