Single Page Sales Promotion Application Using PHP, jQuery, Ajax and PHPMailer Part -2

Posted by & filed under Ajax, CSS, HTML5, JAVASCRIPT, JQUERY, PHP, Twitter Bootstrap.

This is two part tutorial, So please refer my previous tutorial before continuing this one. In this two part I am going to explain step by step how I have created Smart Invoice System Version 3 Single Page Sales Promotion Application.

  1. Single Page Sales Promotion Application Using PHP, jQuery, Ajax and PHPMailer

Single Page Sales Promotion Application Using PHP, jQuery, Ajax and PHPMailer

After user entered their name and email, We are posting those data to PHP. Where the PHP will sending an email as well as save those details in MySQL database. For sending an email, we are using PHPMailer.

In order to use PHPMailer, Either we need to install via Composer or download directly from PHPMailer GitHub page.

Handling PHP Plugins installation and updation via Composer is very easy, So I am going install PHPMailer using Composer.

Before you start installation via Composer, you must installed Composer before using it. So Please install compose using following installation instructions.

Install Composer In XAMPP/WAMP Windows

Notes:

  1. We are sending response back to the front end using proper HTTP STATUS CODE and message.
  2. We usually send 200 HTTP STATUS code, even though the request we made was bad/exception. Because of that in front end we need to handle everything in the success callback even if it’s error/exception response. That consider to be a bad practice.
  3. Always sending resposne with proper HTTP STATUS CODE will help front end developer to handle the success and error effectively in their respective callback function.

Step 1: Install PHPMailer Via Composer

Once you successfully installed Composer in your system. Then open your command prompt and navigate to your project root folder using cd D:\wamp\www\projects\promtion-page.

Now run the following Composer Command in your command terminal


composer require phpmailer/phpmailer

PHPMailer Installation Via Composer PHP

PHPMailer Installation Via Composer PHP

If you don’t want to install via Composer, then download PHPMailer from GitHub and add it your project directly.

If you want any of my script need to be customized according to your business requirement,

Please feel free to contact me [at] muni[at]smarttutorials.net

Note: But it will be charged based on your customization requirement

Step 2: Define Site Wide Configurations in config.php

Create config.php file and define the following site wide configs in it. where I am keeping the Gmail SMTP details and MySQL database credentials.


<?php

//Mail Configuration
const SMTP = true;
const SMTP_HOST = "smtp.gmail.com";
const SMTP_AUTH = true;
const SMTP_USERNAME = "your@gmail.com";
const SMTP_PASSWORD = "your-gmail-password";
const SMTP_SECURE = "tls";
const SMTP_PORT = 587;

const TO_EMAIL = "muni2explore@gmail.com";

//MySQL
define('BASE_PATH', 'http://localhost/projects/promtion-page/');
define('HOST', 'localhost');
define('DB_NAME', "smart_invoice_promotion");
define('DB_USER', "root");
define('DB_PASSWORD', "");

Step 3: Create ajax.php and Include PHPMailer

Next create ajax.php file, which will handle user posted data in PHP (Backend). First include config.php and vendor/autoload.php files in the top of the ajax.php file. Where vendor/autoload.php file generated by Composer, which will handles autoloading of required classes whenever the classes required.


<?php
require_once 'config.php';
require 'vendor/autoload.php';

Next define response array with default data in it. This response array will be sent as an ajax response to the front end based on the operation status.


$response = [
	'status' => 'success',
	'message' => 'Mail sent successfully',
	'data' => []
];

Step 4: Check Ajax Requst In PHP

Next I am checking whether request received by ajax.php file is a valid ajax request or not. If it is not a valid ajax request, then I am sending response back with http_status_code ‘403’ and response array of data.

If it’s valid ajax request, then I am checking whether the request has post data in it or not. If there is no posted data, then I am sending response back with http_status_code ‘400’ and response array of data.


//Checking is it ajax request
if (strtolower($_SERVER['HTTP_X_REQUESTED_WITH']) === 'xmlhttprequest') {
  	
    if( !isset($_POST['data']) ) {
        http_response_code(400);
		$response = [
			'status' => 'error',
			'message' => 'Empty post data.',
			'data' => []
		];
		responseHandler($response);
    }
    
	
} else {
	//Invalid Ajax request
	http_response_code(403);
	$response = [
		'status' => 'error',
		'message' => 'Invalid request, please try again.',
		'data' => []
	];
	responseHandler($response);
}

Step 5: Define Reponse Handler Function

Next define Response Handler function which will send response back to the front end with content-type “application/json” and echo $response array using json_encode.

Note: End of the function add exit statement, otherwise it will continue execution unnecessarily.


/**
 * responseHandler function
 * @param array $response request response
 */
function responseHandler($response)
{
	header('Content-type: application/json');
	echo json_encode($response);
	exit;
}

Step 6: Validate Email And Name Format In PHP

Next we are validating Email and Name Format using following PHP Script, If email/name is not in proper format. Then it will send the proper response back to the front end with proper http status code.


$email = trim($data["userEmail"]);
//Email validation
if ( filter_var($email, FILTER_VALIDATE_EMAIL) === false){
	http_response_code(400);
	$response = [
		'status' => 'error',
		'message' => 'Please provide valid email address.',
		'data' => []
	];
	responseHandler($response);
}

//Name validation
$name = $data["userName"];
if (!preg_match("/^[a-zA-Z ]*$/",$name)) {
	http_response_code(400);
	$response = [
		'status' => 'error',
		'message' => 'Only letters and white space allowed for name..',
		'data' => []
	];
	responseHandler($response);
}

Step 7: Check Email Existence and Send An Email

Next I will check whether email already exists with us or not. If email exists then I will send response back with proper code and message.

If email not exists, then I will send an email as well as save in the database. Finally send a response with proper code (200) and message.


$count = getEmailCount($email);
    
if( $count > 0) {
	http_response_code(400);
	$response = [
		'status' => 'error',
		'message' => 'Your email already with us, We will send you updated to your inbox very soon!!!.',
		'data' => []
	];
	responseHandler($response);
}

$subject = "Smart Invoice V3 Promotion Inquiry";
$message = " {name} ($email) is interested smart invoice version 3.";
$parameters = ['name' => $name ];
if(! send_mail( $email, $subject, $message, $parameters ) ){ 
	//Email sent failed.
	http_response_code(500);
	$response = [
		'status' => 'error',
		'message' => 'Email service failing temporarily Or Maybe you are entered invalid E-mail, Please enter valid email and try again.',
		'data' => []
	];
	responseHandler($response);
} else {
	//Email successfully sent
	saveData([ 
		'email' => $email, 
		'name' => $name
	]);
	http_response_code(200);
	responseHandler($response);
}

Step 7: Define Database Connection, Email Count and Save Data Handler Function

Following three functions which will handle the creation of database connection, getting email count and save posted data in MySQL database.


function getDBConnection()
{
    try {
	  $DBH = new PDO("mysql:host=".HOST.";dbname=".DB_NAME, DB_USER, DB_PASSWORD);
	  $DBH->setAttribute( PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION );
	}
	catch(PDOException $e) {
		echo "I'm sorry, Dave. I'm afraid I can't do that.";
		return;
	}
    
    return $DBH;
}

function getEmailCount($email)
{    
    $DBH = getDBConnection();
    $stmt = $DBH->prepare("SELECT count(*) as cnt FROM `invoice_promotions` WHERE email = :email");
    $stmt->bindParam(':email', $email);
    $isQueryOk = $stmt->execute();
    return $stmt->fetchColumn();
}

function saveData($options)
{
	$DBH = getDBConnection();
    try {
        $STH = $DBH->prepare("INSERT INTO invoice_promotions (name, email) value (:name, :email)");
        $STH->execute($options);
    } catch (PDOException $e) {
        return $e->getMessage();
    }
}

Step 8: Define Email Handler

Define Email handler function, which will send an email to specified email address.


/**
 * send_mail function
 * @param  string $email             [[Description]]
 * @param  string $Subject           [[Description]]
 * @param  string $message           [[Description]]
 * @param  array [$parameters = []] [[Description]]
 * @return boolean  [[Description]]
 */

function send_mail($email, $Subject, $message, $parameters = []){
	
	if( !empty( $parameters ) )$message = parse($message, $parameters);
	
	$mail = new PHPMailer;
	//$mail->SMTPDebug = 3;                               // Enable verbose debug output
	$mail->isSMTP();                                      // Set mailer to use SMTP
	$mail->Host = SMTP_HOST;  // Specify main and backup SMTP servers
	$mail->SMTPAuth = SMTP_AUTH;                               // Enable SMTP authentication
	$mail->Username = SMTP_USERNAME;
	$mail->Password = SMTP_PASSWORD;
	$mail->SMTPSecure = SMTP_SECURE;                            // Enable TLS encryption, `ssl` also accepted
	$mail->Port = SMTP_PORT;                                    // TCP port to connect to
	
	$mail->setFrom($email, 'Smart Invoice V3 Promotion');
	$mail->addAddress(TO_EMAIL);     // Add a recipient
	$mail->addReplyTo($email, 'Smart Invoice V3 Promotion');
	
	$mail->isHTML(true);                                  // Set email format to HTML
	$mail->Subject = $Subject;
	
	$mail->Body = $message;
	$mail->AltBody = strip_tags($message);
	
	if(!$mail->send()) {
//		echo 'Message could not be sent.';
//		echo 'Mailer Error: ' . $mail->ErrorInfo;
        return false;
	} 
	return true;
}

Step 8: Ajax Response Handler

When user clicking ‘Sign Up’ button, I am making ajax request to ajax.php file. Where ajax.php file will process the request and send us back with proper status code and message.

Based on the HTTP_STATUS_CODE, it will call success/error callback. Where success/error callback function will show proper status to the user.


$(document).on('click', '#sendMailBtn', function(e){  
	e.preventDefault();
	if( $('#emailForm').valid() ) {
		var sendMailBtn = $('#sendMailBtn');
		sendMailBtn.button('loading');
		$.ajax({
			url: 'ajax.php',
			method: 'post',
			dataType: 'json',
			data : { data: JSON.stringify($('#emailForm').serializeObject()) },
			success: function( response ){
				sendMailBtn.button('reset');
				$('input').val('');
				showSuccessMessage();
			},
			error: function( response ) {
				sendMailBtn.button('reset');
				if( response.status === 400 || response.status === 403 || response.status === 500 ) {
					showWarningMessage(response.responseJSON.message);
				} else {
					showWarningMessage();
				}
			}
		});
	}

	return false;
});

function showSuccessMessage(){
	swal({
		title: "Many Thanks!!!",
		text: "Thanks for contacting us, We will get back to your inbox shortly...",
		type: "success"
		/*imageUrl: "img/thumbs-up.jpg"*/
	});
}

function showWarningMessage(message){
	if(typeof message === 'undefined' || message === '' ) message = "Something went wrong, Please try again.";
	swal({
		title: "Oops...",
		text: message,
		type: "error"
	});
}

$.fn.serializeObject = function()
{
	var o = {};
	var a = this.serializeArray();
	$.each(a, function() {
		if (o[this.name] !== undefined) {
			if (!o[this.name].push) {
				o[this.name] = [o[this.name]];
			}
			o[this.name].push(this.value || '');
		} else {
			o[this.name] = this.value || '';
		}
	});
	return o;
};

Download Premium Only Scripts & 80+ Demo scripts Instantly at just 1.95 USD per month + 10% discount to all Exclusive Scripts

If you want any of my script need to be customized according to your business requirement,

Please feel free to contact me [at] muni2explore[at]gmail.com

Note: But it will be charged based on your customization requirement

Get Updates, Scripts & Other Useful Resources to your Email

Join 10,000+ Happy Subscribers on feedburner. Click to Subscribe (We don't send spam)
Every Email Subsciber could have access to download 100+ demo scripts & all future scripts.

Get Instant Script Download Access!