PHP Ajax Responsive Contact Form Using jQuery, Bootstrap 3

Posted by & filed under JAVASCRIPT, JQUERY, PHP.

It is not good user interface that has too many page loads. So I am implementing php ajax contact form using jQuery and Bootstrap3 in this tutorial. Please follow this tutorial step by step to implement in your application.

PHP Ajax Responsive Contact Form Using jQuery, Bootstrap 3

Step 1: Create HTML5 Responsive Contact Form Using Bootstrap 3

Create your HTML5 Responsive Contact Form Using Bootstrap 3 or your own. I have created the contact form with four fields (Name, Email, Subject and Message). Here is the HTML5 markup of the contact form.

    
<div class="email-from">
    <form id="emailForm">
       <div class="form-group">
            <label for="userName">Name</label>
            <input type="text" class="form-control" name="userName" id="userName" placeholder="Your Name">
            <span class="help-block"></span>
        </div>
        <div class="form-group">
            <label for="userEmail">Email address</label>
            <input type="email" class="form-control" name="userEmail" id="userEmail" placeholder="Your Email Address">
            <span class="help-block"></span>
        </div>
        <div class="form-group">
            <label for="subject">Subject</label>
            <input type="text" class="form-control" name="subject" id="subject" placeholder="Enter Contact Subject">
            <span class="help-block"></span>
        </div>
        <div class="form-group">
            <label for="message">Your Sweet Message</label>
            <textarea name="message" id="message" rows="6" class="form-control"></textarea>
            <span class="help-block"></span>
        </div>
        <button id="sendMailBtn" data-loading-text="Please Wait..."  type="button" class="btn btn-success form-control">Send Request</button>
    </form>
</div>
    

Step 2: Validate HTML5 Form Using jQuery Validation Plugin

Next we need to validate the Ajax contact form we have created using jQuery validation plugin. Please refer this following steps in that tutorial, how to validate Ajax contact form using jQuery validation plugin.

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

Step 3: Post HTML5 Form Using jQuery Ajax

When user clicks on the ‘Send Request’ button, I am checking either the form is passing all the validation rules defined. If the all the validation rules are passed, then in the submitHandler returning false to avoid normal form submission.

    
     submitHandler : function(form) {
            return false;
        }
    

Next If the all the validation rules are passed, then I am posting form data to ajax.php file using jQuery ajax.

    
     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,textarea').val('');
                showSuccessMessage();
            },
            error: function( response ) {
                sendMailBtn.button('reset');
                if( response.status === 400 || response.status === 403 || response.status === 500 ) {
                    showWarningMessage(response.responseJSON.message);
                } else {
                    showWarningMessage();
                }
            }
        });
    }
    

Step 4: Send mail in PHP Using PHPMailer

First install PHPMailer using Composer or download PHPMailer from their GitHub into your project root folder. Please follow this tutorial to Install PHPMailer Using Composer

How to Install PHPMailer Using Composer.

Next include PHPMailer into ajax.php file and send mail like this…

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

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



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

//Email validation
if ( isset($data["userEmail"]) && !empty( $data["userEmail"] ) ) {
    $email = trim($data["userEmail"]);
    if ( filter_var($email, FILTER_VALIDATE_EMAIL) === false){
        $errors .= "$email is <strong>NOT</strong> a valid email address.<br/>";
    }
} else {
    $errors .= 'Please enter your email address.<br/>';
}
//Name Validation
if ( isset($data["userName"]) && !empty( $data["userName"] ) ) {
    $name = trim( $data["userName"] );
    if ( filter_var($name, FILTER_SANITIZE_STRING) === false){
        $errors .= 'Please enter a valid name.<br/>';
    } elseif (!preg_match("/^[a-zA-Z ]*$/",$name)) {
        $errors .= 'Only letters and white space allowed for name...<br/>';
    }
} else {
    $errors .= 'Please enter your name.<br/>';
}

//Subject Validation
if ( isset($data["subject"]) && !empty( $data["subject"] ) ) {
    $subject = trim( $data["subject"] );
    if ( filter_var($subject, FILTER_SANITIZE_STRING) === false){
        $errors .= 'Please enter a subject to send.<br/>';
    }
} else {
    $errors .= 'Please enter a subject to send.<br/>';
}

//Message Validation
if ( isset($data["message"]) && !empty( $data["message"] ) ) {
    $message = trim( $data["message"] );
    if ( filter_var($message, FILTER_SANITIZE_STRING) === false){
        $errors .= 'Please enter a message to send.<br/>';
    }
} else {
    $errors .= 'Please enter a message to send.<br/>';
}



if(!empty( $errors )) {
    http_response_code(400);
    $response = [
        'status' => 'error',
        'message' => $errors,
        'data' => []
    ];
    responseHandler($response);
}

//Filtering out newlines in the email subject
$subject = str_replace(array("\r","\n"),array(" "," "),$subject);
$contactContent = file_get_contents('email_templates/contact.html');;
$parameters = ['name' => $name, 'to_name' => TO_NAME, 'message' => $message ];

if(! send_mail( $email, $subject, $contactContent, $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
    http_response_code(200);
    responseHandler($response);
} 

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

/**
 * 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 = []){
	////Parse the message with given 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
	
    if( isset($parameters['name']) )  
        $mail->setFrom($email, $parameters['name']);
    else 
        $mail->setFrom($email);
    
    
	$mail->addAddress(TO_EMAIL);     // Add a recipient
	//$mail->addReplyTo($email, 'Smart Invoice V3 Promotion');
    $mail->addBCC(TO_EMAIL);
	
	$mail->isHTML(true);                                  // Set email format to HTML
	$mail->Subject = $Subject;
	
	$mail->Body = $message;
	$mail->AltBody = strip_tags($message);
	
	if(!$mail->send()) {//$mail->ErrorInfo;
        return false;
	} 
	return true;
}


/**
 * parse function
 * @param  string $message    [[Description]]
 * @param  array $parameters [[Description]]
 * @return string [[Description]]
 */
function parse($message, $parameters) {
	foreach ($parameters as $key => $value) {
		$message = str_replace('{'.$key.'}', $value, $message);
	}
	return $message;
}
    

Also refer following which related to sending mails via jQuery Ajax using PHPMailer..

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

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

  3. PHP Gmail SMTP setup for PHPMailer

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.

%d bloggers like this:

Get Instant Script Download Access!