CodeIgniter Form Submission using MySQL, jQuery and Ajax with custom Validation
In this tutorial, you will learn how to submit a form using MySQL, jQuery and Ajax with custom Validation. Here, I have created a responsive Bootstrap form which will take some inputs from you such as full name, Email, Contact No. and comment. You can view the live demo from the Demo link and can download the full live demo script from the Download.
Step 1: Create MySQL Database and Table
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 |
<?php 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.
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 |
<?php /* * 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.
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 |
<?php /* * 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
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 |
<?php $this->load->view('templates/header'); ?> <div class="row"> <div class="col-lg-12"> <h2>CodeIgniter Form Submission Using jQuery Ajax with custom Validation</h2> </div> </div><!-- /.row --> <div class="row"> <div class="col-lg-12"> <a href="#" class="pull-right btn btn-info btn-xs" style="margin: 2px;"><i class="fa fa-mail-reply"></i> Back To Tutorial</a> </div> </div><!-- /.row --> <br> <div class="row"> <div class="col-lg-12"> <span id="success-msg"></span> </div> </div> <form class="contact-frm" id="contact-frm"> <div class="row"> <div class="col-lg-12"> <div class="form-group"> <div class="input-group"> <span class="input-group-addon"> <i class="fa fa-user-o"></i> </span> <input type="text" name="name" class="form-control input-contact-name" id="name" placeholder="Full Name"> </div> </div> </div> </div> <div class="row"> <div class="col-lg-6"> <div class="form-group"> <div class="input-group"> <span class="input-group-addon"> <i class="fa fa-envelope"></i> </span> <input type="text" name="email" class="form-control input-contact-email" id="email" placeholder="Email"> </div> </div> </div> <div class="col-lg-6"> <div class="form-group"> <div class="input-group"> <span class="input-group-addon"> <i class="fa fa-phone"></i> </span> <input type="text" name="contact_no" class="form-control input-contact-contactno" id="contact-no" placeholder="Contact No."> </div> </div> </div> <div class="col-lg-12"> <div class="form-group"> <div class="input-group"> <span class="input-group-addon"> <i class="fa fa-comments"></i> </span> <textarea name="comment" cols="3" rows="5" class="form-control input-contact-comment" id="comment" placeholder="Comments"></textarea> </div> </div> </div> </div> <div class="row"> <div class="col-lg-12 text-right"> <button type="reset" name="reset_add_contact" id="re-info-contact" class="btn btn-danger"><i class="fa fa-undo"></i> Reset</button> <button type="button" name="contact_submit" id="info-contact" class="btn btn-primary"><i class="fa fa-paper-plane"></i> Send</button> </div> </div> </form> <?php $this->load->view('templates/footer'); ?> |
Step 5: Create a file custom.js
Create a view 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 42 43 |
jQuery(document).on('click', 'button#info-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#info-contact').button('loading'); }, complete: function () { jQuery('button#info-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('<div class="text-danger" style="font-size: 14px;">' + json['error'][i] + '</div>'); } else { $(element).after('<div class="text-danger" style="font-size: 14px;">' + json['error'][i] + '</div>'); } } } else { jQuery('span#success-msg').html('<div class="alert alert-success">Your form has been successfully submitted.</div>'); } }, 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:
1 2 3 4 |
<?php // routes $route['default_controller'] = 'contact/index'; ?> |