Create AJAX Contact Form in CodeIgniter and Send Email via SMTP Server
A contact page is a standard web page on a website used to allow the visitor to contact the website owner.CodeIgniter AJAX contact form is used to send contact information without page refresh and use both side validation client and server. In this tutorial, We have to share a simple AJAX-based Contact Form in CodeIgniter and Send Email via SMTP Server. The post covered in easy steps with a live demo to create AJAX Contact Form in CodeIgniter with Email. This is a very simple example, you can just copy-paste, and change according to your requirement.
Before started to implement the Create AJAX Contact Form in CodeIgniter and Send Email via SMTP Server, look files structure:
- codeigniter-create-ajax-contact-form-smtp
- application
- config
- autoload.php
- constants.php
- routes.php
- controllers
- Contact.php
- views
- contact
- index.php
- templates
- header.php
- footer.php
- contact
- config
- system
- index.php
- assets
- css
- style.css
- js
- common.js
- application
Step 1: Load “email” class in controller.
1 2 3 |
<?php $this->load->library('email'); ?> |
Step 2: Define constant
Update file named
constants.php
inside “application/config/” folder.
1 2 3 4 5 6 7 8 9 10 11 12 13 14 |
<?php define('TO_MAIL', 'xxxxx@xxx.com'); define('FROM_MAIL', 'xxxxx@xxx.com'); define('FROM_TEXT', 'TECHARISE'); define('DATE_FORMAT_SIMPLE', 'Y-m-d'); define('PROTOCOL', 'smtp'); define('SMTP_HOST', 'smtp.gmail.com'); define('SMTP_PORT', 587); define('SMTP_USER', 'XXXXX'); define('SMTP_PASS', 'XXXXX'); define('MAILTYPE', 'html'); define('CHARSET', 'utf-8'); ?> |
Step 3: Create a controller file
Create a controller file named
Contact.php
inside “application/controllers” folder.
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 |
<?php /** * @package Contact : CodeIgniter Ajax Contact Form * * @author TechArise Team * * @email info@techarise.com * * Description of Contact Controller */ if (!defined('BASEPATH')) exit('No direct script access allowed'); class Contact extends CI_Controller { public function __construct() { parent::__construct(); } // contact public function index() { $data['page'] = 'ajax-contact'; $data['title'] = 'Create AJAX Contact Form in CodeIgniter and Send Email via SMTP Server | TechArise'; $this->load->view('contact/index', $data); } // send information public function sendData() { $json = array(); $name = $this->input->post('name'); $email = $this->input->post('email'); $contactNo = $this->input->post('contactno'); $comment = $this->input->post('comment'); // name validation if(empty(trim($name))){ $json['error']['name'] = 'Please enter full name'; } // email validation if(empty(trim($email))){ $json['error']['email'] = 'Please enter email address'; } // check email validation if ($this->validateEmail($email) == FALSE) { $json['error']['email'] = 'Please enter valid email address'; } // check conatct no validation if($this->validateMobile($contactNo) == FALSE) { $json['error']['contactno'] = 'Please enter valid contact no. format: 9000000001'; } // comment validation if(empty($comment)){ $json['error']['comment'] = 'Please enter comment'; } if(empty($json['error'])){ // load email lib $this->load->library('email'); //SMTP & mail configuration $config = array( 'protocol' => PROTOCOL, 'smtp_host' => SMTP_HOST, 'smtp_port' => SMTP_PORT, 'smtp_user' => SMTP_USER, 'smtp_pass' => SMTP_PASS, 'mailtype' => MAILTYPE, 'charset' => CHARSET, ); $message=''; $bodyMsg = '<p style="font-size:14px;font-weight:normal;margin-bottom:10px;margin-top:0;">'.$comment.'</p>'; $delimeter = $name."<br>".$contactNo; $dataMail = array('topMsg'=>'Hi Team', 'bodyMsg'=>$bodyMsg, 'thanksMsg'=>'Best regards,', 'delimeter'=> $delimeter); $this->email->initialize($config); $this->email->from($email, $name); // set to email $this->email->to(TO_MAIL); $this->email->subject('Contact Form'); // call mail Template $message = $this->load->view('mailTemplate/contactForm', $dataMail, TRUE); $this->email->message($message); $status = $this->email->send(); // confirmation mail $bodyMsg = '<p style="font-size:14px;font-weight:normal;margin-bottom:10px;margin-top:0;">Thank you for contacting us.</p>'; $dataMail = array('topMsg'=>'Hi '.$name, 'bodyMsg'=>$bodyMsg, 'thanksMsg'=>'Best regards,', 'delimeter'=> 'Team TechArise'); $this->email->initialize($config); $this->email->from(TO_MAIL, FROM_TEXT); $this->email->to($email); $this->email->subject('Contact Form Confimation'); // call confirmation Template $message = $this->load->view('mailTemplate/contactForm', $dataMail, TRUE); $this->email->message($message); $status = $this->email->send(); if(!empty($status)){ $json['msg'] = 'success'; } else { $json['msg'] = 'failed'; } } $this->output->set_header('Content-Type: application/json'); echo json_encode($json); } // check email validation public function validateEmail($email) { return preg_match('/^[^\@]+@.*.[a-z]{2,15}$/i', $email)?TRUE:FALSE; } // check mobile validation public function validateMobile($mobile) { return preg_match('/^[0-9]{10}+$/', $mobile)?TRUE:FALSE; } } ?> |
Step 4:Create a view(header)
Create a view file named header.php inside “application/views/templates” folder.
This view contains the header section of the webpage. The Bootstrap library is used to provide a better UI, so, include it in the header section.
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 |
<?php defined('BASEPATH') OR exit('No direct script access allowed'); ?> <!DOCTYPE html> <html lang="en"> <head> <meta charset="utf-8"> <meta name="viewport" content="width=device-width, initial-scale=1, shrink-to-fit=no"> <meta name="description" content=""> <meta name="author" content=""> <title><?php print $title; ?></title> <link rel="icon" type="image/ico" href="<?php print HTTP_IMAGE_PATH; ?>favicon.ico"> <!-- Bootstrap core CSS --> <link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/twitter-bootstrap/4.3.1/css/bootstrap.min.css" /> <!-- Custom fonts for this template --> <link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/font-awesome/5.7.2/css/all.min.css" /> <link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/simple-line-icons/2.4.1/css/simple-line-icons.css" /> <link href="https://fonts.googleapis.com/css?family=Lato:300,400,700,300italic,400italic,700italic" rel="stylesheet" type="text/css"> <!-- Custom styles for this template --> <link href="<?php print HTTP_CSS_PATH; ?>style.css" rel="stylesheet"> </head> <body> <!-- Navigation --> <nav class="navbar navbar-expand-lg navbar-dark bg-dark static-top header-bg-dark" style="background: ##FFFFFF!;"> <div class="container"> <a class="navbar-brand font-weight-bold" href="https://techarise.com"><h1>Tech Arise</h1></a> <button class="navbar-toggler" type="button" data-toggle="collapse" data-target="#navbarResponsive" aria-controls="navbarResponsive" aria-expanded="false" aria-label="Toggle navigation"> <span class="navbar-toggler-icon"></span> </button> <div class="collapse navbar-collapse" id="navbarResponsive"> <ul class="navbar-nav ml-auto"> <li class="nav-item active"> <a class="nav-link" href="https://techarise.com">Home <span class="sr-only">(current)</span> </a> </li> <li class="nav-item"> <a class="nav-link" href="https://techarise.com/php-free-script-demos/">Live Demo</a> </li> </ul> </div> </div> </nav> |
Step 5: Create a view(footer)
Create a view file named footer.php inside “application/views/templates” folder.
This view contains the footer section of the webpage.
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 |
<!-- Footer --> <footer class="footer bg-light footer-bg-dark"> <div class="container"> <div class="row"> <div class="col-lg-6 h-100 text-center text-lg-left my-auto"> <ul class="list-inline mb-2"> <li class="list-inline-item"> <a href="#">About</a> </li> <li class="list-inline-item">⋅</li> <li class="list-inline-item"> <a href="#">Contact</a> </li> <li class="list-inline-item">⋅</li> <li class="list-inline-item"> <a href="#">Terms of Use</a> </li> <li class="list-inline-item">⋅</li> <li class="list-inline-item"> <a href="#">Privacy Policy</a> </li> </ul> <p class="text-muted small mb-4 mb-lg-0">Copyright © 2011 - <?php print date('Y', time());?> <a href="https://techarise.com/">TECHARISE.COM</a> All rights reserved.</p> </div> <div class="col-lg-6 h-100 text-center text-lg-right my-auto"> <ul class="list-inline mb-0"> <li class="list-inline-item mr-3"> <a href="#"> <i class="fab fa-facebook fa-2x fa-fw"></i> </a> </li> <li class="list-inline-item mr-3"> <a href="#"> <i class="fab fa-twitter-square fa-2x fa-fw"></i> </a> </li> <li class="list-inline-item"> <a href="#"> <i class="fab fa-instagram fa-2x fa-fw"></i> </a> </li> </ul> </div> </div> </div> </footer> <script> var baseurl = ""; </script> <!-- Bootstrap core JavaScript --> <script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script> <script src="https://cdnjs.cloudflare.com/ajax/libs/twitter-bootstrap/4.3.1/js/bootstrap.bundle.min.js"></script> <script type="text/javascript" src="<?php print HTTP_JS_PATH; ?>/common.js"></script> </body> </html> |
Step 5: Create a view
Create a view file named
index.php
inside “application/views/contact” folder.
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 |
<?php $this->load->view('templates/header'); ?> <section class="showcase"> <div class="container"> <div class="pb-2 mt-4 mb-2 border-bottom"> <h2>Create AJAX Contact Form in CodeIgniter and Send Email via SMTP Server</h2> </div> <div class="row"> <div class="col-md-12"><span id="success-msg"></span></div> </div> <div class="row"> <div class="col-md-12 gedf-main"> <form class="ajax-contact-frm" id="ajax-contact-frm"> <div class="input-group mb-3"> <div class="input-group-prepend"> <span class="input-group-text" id="basic-addon1"><i class="fa fa-user"></i></span> </div> <input type="text" name="name" class="form-control input-acf-name" id="name" placeholder="Full Name"> </div> <div class="input-group mb-3"> <div class="input-group-append"> <span class="input-group-text" id="basic-addon2"><i class="fa fa-envelope"></i></span> </div> <input type="text" name="email" class="form-control input-acf-email" id="email" placeholder="Email"> </div> <div class="input-group mb-3"> <div class="input-group-append"> <span class="input-group-text" id="basic-addon3"><i class="fa fa-phone"></i></span> </div> <input type="text" name="contactno" class="form-control input-acf-contactno" id="contact-no" placeholder="Contact No."> </div> <div class="input-group mb-3"> <div class="input-group-append"> <span class="input-group-text" id="basic-addon4"><i class="fa fa-comments"></i></span> </div> <textarea name="comment" cols="3" rows="5" class="form-control input-acf-comment" id="comment" placeholder="Comments"></textarea> </div> <div class="col-md-12 text-right"> <button type="reset" name="reset_col" class="btn btn-danger"><i class="fa fa-undo"></i> Reset</button> <button type="button" name="send_query" class="btn btn-primary" id="send-query"><i class="fa fa-paper-plane"></i> Send</button> </div> </form> </div> </div> </div> </section> <?php $this->load->view('templates/footer'); ?> |
Step 6: Create a view(mailTemplate)
Create a view file named
contactForm.php
inside “application/views/mailTemplate” folder
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 |
<html xmlns="http://www.w3.org/1999/xhtml"> <head> <meta http-equiv="Content-Type" content="text/html; charset=utf-8" /> <meta name="viewport" content="width=device-width"/> </head> <body style="width:100%;height:100%;background:#efefef;-webkit-font-smoothing:antialiased;-webkit-text-size-adjust:none;color:#3E3E3E;font-family:Helvetica, Arial, sans-serif;line-height:1.65;margin:0;padding:0;"> <table border="0" cellpadding="0" cellspacing="0" style="width:100%;background:#efefef;-webkit-font-smoothing:antialiased;-webkit-text-size-adjust:none;color:#3E3E3E;font-family:Helvetica, Arial, sans-serif;line-height:1.65;margin:0;padding:0;"> <tr> <td valign="top" style="display:block;clear:both;margin:0 auto;max-width:580px;"> <table border="0" cellpadding="0" cellspacing="0" style="width:100%;border-collapse:collapse;"> <tr> <td valign="top" align="center" class="masthead" style="padding:20px 0;background:#03618c;color:white;"> <h1 style="font-size:32px;margin:0 auto;max-width:90%;line-height:1.25;"> <a href="<?php print site_url(); ?>" target="_blank" style="text-decoration:none;color:#ffffff;">TECHARISE</a> <p style="margin-bottom:0;line-height:12px;font-weight:normal;margin-top:15px;font-size:18px;"></p> </h1> </td> </tr> <tr> <td valign="top" class="content" style="background:white;padding:20px 35px 10px 35px;"> <h4 style="font-size:20px;margin-bottom:10px;line-height:1.25;"><?php print $topMsg; ?>,</h4> <?php print $bodyMsg; ?> </td> </tr> <tr> <td valign="top" style="display:block;clear:both;margin:0 auto;max-width:580px;"> <table border="0" cellpadding="0" cellspacing="0" style="width:100%;border-collapse:collapse;"> <tr> <td valign="top" class="content thanksMsg" style="background:white;padding:10px 35px 20px 35px;"> <p style="font-size:14px;font-weight:normal;margin-top:0;margin-bottom:5px;"><?php print $thanksMsg; ?></p> <p style="font-size:14px;font-weight:normal;margin-top:0;margin-bottom:5px;"><?php print $delimeter; ?></p> </td> </tr> </table> </td> </tr> </table> </td> </tr> </table> </body> </html> |
Step 7: Create a AJAX file
Create a js file named
custom.js
inside “assets/js” folder.
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 |
jQuery(document).on('click', 'button#send-query', function() { jQuery.ajax({ type:'POST', url:baseurl+'contact/sendData', data:jQuery("form#ajax-contact-frm").serialize(), dataType:'json', beforeSend: function () { jQuery('button#send-query').button('loading'); }, complete: function () { jQuery('button#send-query').button('reset'); jQuery("form#ajax-contact-frm").find('textarea, input').each(function () { jQuery(this).val(''); }); setTimeout(function () { jQuery('span#success-msg').html(''); }, 4000); }, success: function (json) { $('.text-danger').remove(); if (json['error']) { for (i in json['error']) { var element = $('.input-acf-' + i.replace('_', '-')); if ($(element).parent().hasClass('input-group')) { $(element).parent().after('<small class="text-danger">' + json['error'][i] + '</small>'); } else { $(element).after('<small class="text-danger">' + json['error'][i] + '</small>'); } } } else { jQuery('span#success-msg').html('<div class="alert alert-success" role="alert">Your query has been successfully submitted.</div>'); } }, error: function (xhr, ajaxOptions, thrownError) { console.log(thrownError + "\r\n" + xhr.statusText + "\r\n" + xhr.responseText); } }); }); |