Fast way to setup a form with PHPMailer and Ajax

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 PHPMailer(true);                              // Passing `true` enables exceptions
try {
    //Server settings
    $mail->SMTPDebug = 0;                                 // Enable verbose debug output
    $mail->isSMTP();                                      // Set mailer to use SMTP
    $mail->Host = 'smtp.zoho.com';  // Specify main and backup SMTP servers
    $mail->SMTPAuth = true;                               // Enable SMTP authentication
    $mail->Username = '[email protected]';                 // SMTP username
    $mail->Password = 'YOUR PASSWORD';                           // SMTP password
    $mail->SMTPSecure = 'tls';                            // Enable TLS encryption, `ssl` also accepted
    $mail->Port = 587;                                    // TCP port to connect to

    //Recipients
    $mail->setFrom('[email protected]', 'flashsoft.ro Mailer');
    $mail->addAddress('[email protected]', 'Andrei O.');     // Add a recipient             // Name is optional
    $mail->addReplyTo('[email protected]', 'Information');


    //Content
    $mail->isHTML(true);                                  // Set email format to HTML
    $mail->Subject = 'Contact MsG from flashsoft.ro';
    $mail->Body    = 'Message from '.$name.' [ '.$email.' ] Msg:<br>'.$msg;
    $mail->AltBody = 'Message from '.$name.' [ '.$email.' ] Msg:\n'.$msg;


    $mail->send();
	exit(json_encode(['send'=>'success', 'msg'=>'Message has been sent.' ]));
} catch (Exception $e) {
    exit(json_encode(['send'=>'error', 'msg'=>'Message could not be sent. <br>Mailer Error: ' . $mail->ErrorInfo ]));
}


	}else{
	 exit( json_encode(['send'=>'error', 'msg'=>'All fields are required.' ]));
}

now your JS code:

$("#mailForm").submit(function(e) {

    var url = "smail.php"; // the script where you handle the form input.

    $.ajax({
           type: "POST",
           url: url,
           data: $("#mailForm").serialize(), // serializes the form's elements.
           success: function(data)
           {
			   data = JSON.parse(data);
               if(data.send != 'success'){
				   swal("Error!", data.msg, "error");
			   }else{
				    swal("Success!", data.msg, "success");
			   }
           }
         });

    e.preventDefault(); // avoid to execute the actual submit of the form.
});

As you can see from the code above you should import swal and Jquery.

Now the last part a from:

			<form id="mailForm">
				<input name="name" type="text" placeholder="Name" />
				<input name="email" type="email" placeholder="Email"/>
				<textarea name="message" id="message" cols="30" rows="5" placeholder="Message"></textarea>
				  <div class="recaptcha" id="recaptcha_element"></div>
				<button type="submit" value="Send" class="btn-submit"><span class="icon-send-o"></span>&nbsp;Send&nbsp;</button>
			</form>
			    <script src="https://www.google.com/recaptcha/api.js?onload=onloadCallback&render=explicit"
        async defer>

Don’t forget to include also the callback for the script, I did that cause I wanted to use the template dark for the RECAPTCHA V2:

	    <script type="text/javascript">
      var onloadCallback = function() {
        grecaptcha.render('recaptcha_element', {
          'sitekey' : 'secret_key',
		   'theme' : 'dark'
        });
      };
    </script>

And that is pretty much it, using Swal is the lazy way of course if you want to make some custom animations and something more complex than Swal you would have to change the javascript part.

Share the joy

One Response

  1. Eduard January 28, 2018

Leave a Reply