Step 1: Create MySQL Database and Table
CREATE TABLE `contact` (
`id` int(11) NOT NULL,
`name` varchar(255) NOT NULL,
`email` varchar(255) NOT NULL,
`contact_no` varchar(15) NOT NULL,
`comment` text NOT NULL,
`created_date` varchar(12) NOT NULL
) ENGINE=InnoDB DEFAULT CHARSET=latin1;
ALTER TABLE `contact`
ADD PRIMARY KEY (`id`);
ALTER TABLE `contact`
MODIFY `id` int(11) NOT NULL AUTO_INCREMENT;
?>
Step 2: Create a model file Site
Create a model file named Site.php” inside “application/models” folder.
/*
* To change this license header, choose License Headers in Project Properties.
* To change this template file, choose Tools | Templates
* and open the template in the editor.
*/
/**
* @package Razorpay : CodeIgniter Site
*
* @author TechArise Team
*
* @email info@techarise.com
*
* Description of Site Controller
*/
if (!defined('BASEPATH'))
exit('No direct script access allowed');
class Site extends CI_Model {
private $_name;
private $_email;
private $_contactNo;
private $_comment;
private $_timeStamp;
public function setName($name)
{
$this->_name = $name;
}
public function setEmail($email)
{
$this->_email = $email;
}
public function setContactNo($contactNo)
{
$this->_contactNo = $contactNo;
}
public function setComment($comment)
{
$this->_comment = $comment;
}
public function setTimeStamp($timeStamp)
{
$this->_timeStamp = $timeStamp;
}
// save value in database
public function create()
{
$data = array(
'name' => $this->_name,
'email' => $this->_email,
'contact_no' => $this->_contactNo,
'comment' => $this->_comment,
'created_date' => $this->_timeStamp,
);
$this->db->insert('contact', $data);
return $this->db->insert_id();
}
// email validation
public function validateEmail($email)
{
return preg_match('/^[^\@]+@.*.[a-z]{2,15}$/i', $email)?TRUE:FALSE;
}
// mobile validation
public function validateMobile($mobile)
{
return preg_match('/^[0-9]{10}+$/', $mobile)?TRUE:FALSE;
}
}
?>
Step 3: Create a Controller file Contact
Create a Controller file named "Contact.php" inside "application/controllers" folder.
/*
* To change this license header, choose License Headers in Project Properties.
* To change this template file, choose Tools | Templates
* and open the template in the editor.
*/
/**
* @package Contact : CodeIgniter Contact Form Ajax
*
* @author TechArise Team
*
* @email info@techarise.com
*
* Description of Contact Form Ajax Controller
*/
if (!defined('BASEPATH'))
exit('No direct script access allowed');
class Contact extends CI_Controller
{
// construct
public function __construct()
{
parent::__construct();
$this->load->model('Site', 'site');
}
// index page
public function index()
{
$data = array();
$data['metaDescription'] = 'Contact Form Ajax';
$data['metaKeywords'] = 'Contact Form Ajax';
$data['title'] = "Contact Form Ajax - TechArise";
$data['breadcrumbs'] = array(' Contact Form Ajax' => '#');
$this->load->view('contact/index', $data);
}
// submit contact form
// New user registration data handle
public function createUser()
{
$json = array();
$name = $this->input->post('name');
$email = $this->input->post('email');
$contactNo = $this->input->post('contact_no');
$comment = $this->input->post('comment');
$timeStamp = time();
// 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->site->validateEmail($email) == FALSE) {
$json['error']['email'] = 'Please enter valid email address';
}
// check conatct no validation
if($this->site->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'])){
$this->site->setName(trim($name));
$this->site->setEmail($email);
$this->site->setContactNo($contactNo);
$this->site->setComment($comment);
$this->site->setTimeStamp($timeStamp);
try {
$last_id = $this->site->create();
} catch (Exception $e) {
var_dump($e->getMessage());
}
if (!empty($last_id) && $last_id > 0) {
$json['status'] = 'success';
}
}
echo json_encode($json);
}
}
?>
Step 4: Create a view file index
Create a view file named "index.php" inside "application/views/contact" folder
$this->load->view('templates/header');
?>
CodeIgniter Form Submission Using jQuery Ajax with custom Validation
$this->load->view('templates/footer');
?>
Step 5: Create a file custom.js
Create a view file named "custom.js" inside "assets/js" folder
jQuery(document).on('click', 'button#submit-contact', function(){
//alert(jQuery("#register-form").serialize());
jQuery.ajax({
type:'POST',
url:baseurl+'contact/createUser',
data:jQuery("#contact-frm").serialize(),
dataType:'json',
beforeSend: function () {
jQuery('button#submit-contact').button('loading');
},
complete: function () {
jQuery('button#submit-contact').button('reset');
jQuery('#contact-frm').find('textarea, input').each(function () {
jQuery(this).val('');
});
setTimeout(function () {
jQuery('span#success-msg').html('');
}, 3000);
},
success: function (json) {
//console.log(json);
$('.text-danger').remove();
if (json['error']) {
for (i in json['error']) {
var element = $('.input-contact-' + i.replace('_', '-'));
if ($(element).parent().hasClass('input-group')) {
$(element).parent().after('' + json['error'][i] + '');
} else {
$(element).after('' + json['error'][i] + '');
}
}
} else {
jQuery('span#success-msg').html('Your form has been successfully submitted.');
}
},
error: function (xhr, ajaxOptions, thrownError) {
console.log(thrownError + "\r\n" + xhr.statusText + "\r\n" + xhr.responseText);
}
});
});
Step 7: Open file routes
Open "application/config/routes.php" file and add code like as bellow:
// routes
$route['default_controller'] = 'contact/index';
?>
Demo [sociallocker] Download[/sociallocker]