Wednesday, 8 November 2017

How to Optimise A Contact Page With Email Notification Using BootStrap and AJAX/PHP

Leave a Comment
Whao... Here we are again, it's been a long time I feed my readers with a good post. I have been busy programming for the web. I've been writing a lot of code lately but I did something recently that really got my inner man saying "you have to share this with fellow developers". Yes this post is for developers, especially beginner developers. I'm currently working on an e-commerce project that required me to code from scratch using only bootstrap and Jquery framework. I've done much, as a matter of fact the project is 80% completed. What I'm about to share with you is actually a trivial part of the project compared to others tasks such as online payment integration. It's trivial but cool. 

So what am I talking about? It is the contact page of Future Cooperative Stores. Below is a screen shot of the page and the circled portion is what I want to put you through.  It is a quick note form that allow user to send a quick message to the company. 

The popular implementation of this is storing the information in a database which may not be seen until after some time. When users and prospective customers send this kind of messages and don't get a feed back in the next few hours, it may give a negative impression about the customer service of an e-commerce firm. So, after storing the information in a database, an email is sent to whoever is in charge. The email contains all the information filled in by the user. Let's say I filled the form with some information as shown below: 

After storing the information in the database, my web app will send and email that reads A quick note "I want know more about this company" was sent from Ayodele Olufemi with phone number: 07063251851 and email: Please attend to it quickly.

 That's cool right? The person in charge of handling this note is notified on the fly via email. The user get feedback in time and encouraged to patronize the company.
This is done very fast with the help of JavaScript and Ajax without reloading the page. A bootstrap modal is used to notify the user when the message is sent. PHP is used to store the data entered into MySQL database as well as send email but the process is very fast. The process asynchronous, behind the scene. So how was I able to accomplish this? Read on to find out.

 The Codes

 For this implementation, you need to have J QUERY and Bootstrap frameworks. You can search google to download them if you don't have them. Also your database connection have to be set. I will go on to explain the code structure.  

Database Connection
This is not new to the PHP gurus. For reference purpose the database connection (dbconn.php) is as follows:

$user = 'root'; $password = 'password'; $dbase = 'myDb';

$dblink = mysqli_connect('localhost', $user, $password, $dbase);

if (!$dblink) {
    die(('Connect Error ('.mysqli_connect_errno().') '. mysqli_connect_error()));


The database connection is just a format. You have to replace the password and other parameters with your database settings. Of course you don't expect me to reveal my settings.

Table Structure
The table structure can be created with the SQL below. Just dump it in your SQL editor and run it. This is just to illustrate how I accomplish this task. You can modify it to your taste.

CREATE TABLE `quicknotes` (
  `id` int(11) NOT NULL,
  `fullname` varchar(70) NOT NULL,
  `email` varchar(70) NOT NULL,
  `phone` varchar(15) NOT NULL,
  `message` text NOT NULL,

-- Dumping data for table `quicknotes`

ALTER TABLE `quicknotes`

-- AUTO_INCREMENT for dumped tables

-- AUTO_INCREMENT for table `quicknotes`
ALTER TABLE `quicknotes`

Form Processors
The form is processed by two files; a JavaScript file (ajax-pro.php) and a PHP file (cp.php). The JavaScript file takes the information entered using the id from each input tag and send them to cp.php for database operations and email notification using AJAX and J QUERY. The ajax-pro.js also validate the form and manipulate the message modal in when response is gotten from cp.php. below is the content of the ajax-pro.js file. 

$(document).ready(function() {

    //Submit 'Add New' form
    $('#addNewForm').on('submit', function(e) {
        $('#addNewBtn').html(' Sending Message...');
        //Disable button
        $('#addNewBtn').prop('disabled', true);

        //Remove spaces inputs
        var fullname = $.trim($('#fname').val());
        var email = $.trim($('#email').val());
        var msg = $.trim($('#msg').val());
        var phone = $.trim($('#phone').val());

        // Start validation;
        if (fullname !== '' && email !== '' && msg !== '' && phone !== '')

            data: $('#addNewForm').serialize(),
            success: function() {
              $('#message').html('Message sent successfully! Thanks');
              $('#fullname, #email, #msg, #phone').removeClass('correctinput');
              $('#fullname, #email, #msg, #phone').removeClass('errorinput');
              $('input, textarea').val('');

          $('#fullname, #email, #msg, #phone').addClass('errorinput');
          $('#errorMsgNew').html(' Fill all fields');


What follows is the content of our cp.php file. 

/* include_once('assets/inc/navbar.php');
$brandMan = new Main;
$navbar = new Navbar; */

$fname = mysqli_real_escape_string($dblink, trim($_POST['fname']));
$email = mysqli_real_escape_string($dblink, trim($_POST['email']));
$phone = mysqli_real_escape_string($dblink, trim($_POST['phone']));
$message = mysqli_real_escape_string($dblink, trim($_POST['msg']));

mysqli_query($dblink, "INSERT INTO `quicknotes` (`fullname`, `phone`, `email`, `message`) VALUES ('$fname', '$phone', '$email', '$message')") or die($this->dbError(mysqli_error($dblink), $_SERVER['PHP_SELF']));

$to = '';
$subject = "New Quick Note";
$header = "FCS: Quick Note";
$message = "A quick note \"". $message . "\" was sent from " . $fname . " with phone number: " . $phone . " and email: " . $email . ". Please attend to it quickly";

 $sentmail = mail($to,$subject,$message,$header);


 Take note of the first line that include the database connection file we created earlier. This is important for storing form data to database. 

If all is properly set and you carefully follow the this tutorial, your implementation will work fine. Apart from the email optimization, this is a very good way of processing a form. It is fast and seamless. Please do not hesitate to drop your comments/recommendations and questions using the comment box below. Watch out for the SMS version of this tutorial. Instead of getting a mail, the person in charge get notified by SMS. Please share and once again, don't forget to drop your comment. God bless you.
If You Enjoyed This, Take 5 Seconds To Share It


Post a Comment

Add a comment here