Fast way to setup a form with PHPMailer and Ajax
This article has been written before more than 24months, information might old.
PHPMailer is a popular library for sending emails as the project of the title suggest. In the GitHub, readme file has a nice example of a basic setup, but today I’ll give you a similar simple example using jQuery, Swal( Sweet alert ).
So first this is the PHP script that should respond to an ajax request ( I named the filename smail.php):
<?php error_reporting(0); // Import PHPMailer classes into the global namespace // These must be at the top of your script, not inside a function use PHPMailer\PHPMailer\PHPMailer; use PHPMailer\PHPMailer\Exception; //Load composer's autoloader require 'vendor/autoload.php'; function isValidEmail($email){ return filter_var($email, FILTER_VALIDATE_EMAIL) !== false; } $name = htmlspecialchars($_POST["name"]); $email = htmlspecialchars($_POST["email"]); $msg = htmlspecialchars($_POST["message"]); $recap = htmlspecialchars($_POST["g-recaptcha-response"]); $gcapSecret = 'YOUR RECAPTCHA2 SECRET'; if( !empty($name ) && !empty( $email) && !empty( $msg ) ){ if( empty( $recap ) ) exit( json_encode(['send'=>'error', 'msg'=>'Please complete the captcha.' ])); if(!isValidEmail($email)) exit( json_encode(['send'=>'error', 'msg'=>'Invalid Email.' ])); $response=file_get_contents("https://www.google.com/recaptcha/api/siteverify?secret=".$gcapSecret."&response=".$recap."&remoteip=".$_SERVER['REMOTE_ADDR']); $obj = json_decode($response); if($obj->success != true) exit( json_encode(['send'=>'error', 'msg'=>'Google ReCaptcha V2 not passed.' ])); $mail = new…