I will show you how you can create a captcha validation with Codeiginter based on Ajax.
1. Below is my model name as Mcaptcha
- class Mcaptcha extends CI_Model {
- protected $ci;
- function __construct() {
- // Call the Model constructor
- parent::__construct();
- $this->ci =& get_instance();
- }
- function setCaptcha(){
- $this->load->helper('captcha');
- $rand = substr(md5(microtime()),rand(0,26),5);
- $vals = array(
- 'img_path' => FCPATH.'assets/captcha/',
- 'img_url' => base_url().'assets/captcha/',
- 'expiration' => 1800,// half hour
- 'font_path' => FCPATH.'assets/fonts/Cabin-BoldItalic.ttf',
- 'img_width' => '140',
- 'img_height' => 30,
- 'word' => $rand,
- );
- $cap = create_captcha($vals);
- $this->ci->session->set_userdata(array('cpt'=>$rand, 'img' => $cap['time'].'.jpg'));
- return $cap['image'] ;
- }
- }
2. Your controller function will goes like below
- public function send_us_email() {
- $this->load->library('form_validation');
- $this->load->model('mcaptcha');
- $this->form_validation->set_error_delimiters('<span>', '</span>');
- $this->form_validation->set_rules('sname', 'Name', 'trim|required|max_length[20]|xss_clean');
- $this->form_validation->set_rules('captcha', 'Captcha', 'trim|required|max_length[5]|
- callback_validate_captcha|xss_clean');
- if ($this->form_validation->run() == FALSE){
- // if any fields on form not validated properly we need to unset session and unlink captcha
- image previously created and then regenerate captcha and passing it to Cmessage.
- if(file_exists(FCPATH."assets/captcha/".$this->session->userdata['img']))
- unlink(FCPATH."assets/captcha/".$this->session->userdata['img']);
- $this->session->unset_userdata('cpt');
- $this->session->unset_userdata('img');
- $captcha = $this->mcaptcha->setCaptcha();
- echo json_encode(array('Mstatus'=>'error','Cmessage'=>$captcha,'msg' => validation_errors()));
- }else{
- $sname=set_value('sname');
- $captcha=set_value('captcha');
- $data=array('name'=>$sname);
- $send_us_a_email_template= $this->load->view('email_templates/send_us_a_email', $data, true);
- $this->email->from('youremail@domain.com',"YourTITLE");
- $this->email->to($semail);
- $this->email->subject('Customer Query Request');
- $this->email->message($send_us_a_email_template);
- if ($this->email->send()){
- // same logic above if every thing goes well.
- if(file_exists(FCPATH."assets/captcha/".$this->session->userdata['img']))
- unlink(FCPATH."assets/captcha/".$this->session->userdata['img']);
- $this->session->unset_userdata('cpt');
- $this->session->unset_userdata('img');
- echo json_encode(array('Mstatus'=>'success','Cmessage'=>'We have recieved
- your email and we will get back to you shortly. Thanks.','msg'=>''));
- }else{
- echo json_encode(array('Mstatus'=>'error','Cmessage'=>'','msg' => 'Error
- in processing your query. Please try later.'));
- }
- }
- }
3. Below is call back function to validate captcha enter by user.
- public function validate_captcha($str){
- if($str != $this->session->userdata['cpt']){
- $this->form_validation->set_message('validate_captcha', 'Wrong captcha code,
- hmm are you the Terminator?');
- return false;
- }else{
- return true;
- }
- }
4. Your jQuery goes like below
- $(document).ready(function() {
- $('#submit-link-form').bootstrapValidator({
- message: 'This value is not valid',
- feedbackIcons: {
- valid: 'glyphicon glyphicon-ok',
- invalid: 'glyphicon glyphicon-remove',
- validating: 'glyphicon glyphicon-refresh'
- },
- fields: {
- linkname: {
- validators: {
- notEmpty: {
- message: 'The name is required.'
- },
- stringLength: {
- min: 4,
- message: 'Name must be 4 characters long.'
- }
- }
- },
- scaptcha: {
- validators: {
- notEmpty: {
- message: 'Captcha verification is required.'
- }
- }
- }
- }
- })
- .on('success.form.bv', function(e) {
- e.preventDefault();
- var $form = $(e.target);
- var bv = $form.data('bootstrapValidator');
- $.ajax({
- url: $form.attr('action')+'?time='+timestamp,
- type: $form.attr('method'),
- data: $form.serialize(),
- dataType:'json',
- beforeSend: function() {
- },
- complete: function() {
- },
- success: function(response){
- switch(response.Mstatus){
- case 'success':
- break;
- case 'error':
- break;
- default:
- break;
- }
- }
- });
- });
- });
5. Your bootstrap model popup will looks like below
- <div class="container">
- <div class="modal fade animate1 faster-modal" id="send-us-email-modal" tabindex="-1" role="dialog"
- aria-labelledby="sendusemailLabel" aria-hidden="true">
- <div class="modal-dialog">
- <div class="modal-content">
- <div class="modal-header">
- <button type="button" class="close" data-dismiss="modal"><span aria-hidden="true">×</span>
- <span class="sr-only">Close</span></button>
- <h4 class="modal-title" id="sendusemailLabel">Send Us Email</h4>
- </div>
- <div class="modal-body">
- <?php echo form_open(base_url().'root/send_us_email',array('id' =>'send-us-email-form',
- 'name' =>'send-us-email-form','method'=>'post'));?>
- <div class="faster-ajax-loader faster_ajax_loader" style="display:none;"></div>
- <aside class="form-group">
- <div class="popup_message"></div>
- </aside>
- <aside class="form-group">
- <input type="text" class="form-control required" placeholder="Your Name" name="sname" id="sname" />
- </aside>
- <aside class="form-group form-capcha"> <span class="generated-capcha"><img
- src="<?php echo base_url();?>images/default.jpg" width="140" height="30" alt="Verification Code">
- </span><a href="javascript:void(0);" title="Refresh Verification Code">
- <span class="glyphicon glyphicon-refresh refresh-regenerate"></span></a> </aside>
- <aside class="form-group">
- <input class="form-control text required" id="captcha" type="text" name="captcha" value=""
- placeholder="Verification Code" />
- </aside>
- <aside class="form-group">
- <input type="submit" class="btn-features animate1" value="Send Us Email" />
- </aside>
- </form>
- </div>
- </div>
- </div>
- </div>
- </div>
6. If you would like to refresh captcha if it is not visible properly to users then refresh captcha on Link / Image click .Your js code will goes like below
- $(function(){
- $(document).on('click', '.refresh-regenerate', function(){
- var myformclick=$(this).closest('form').attr('id');
- $.ajax({
- url: baseurl+"root/generate_captcha",
- type: "POST",
- data: "cap=1",
- cache: false,
- dataType:'json',
- beforeSend: function() {
- $("#"+myformclick).find(".faster_ajax_loader").css('display','block');
- },
- complete: function() {
- $("#"+myformclick).find(".faster_ajax_loader").css('display','none');
- },
- success: function(response){
- $("#"+myformclick).find(".generated-capcha").html(response.Cmessage);
- }
- });
- });
- });
7. I am calling generate_captcha function so that on each click new captcha image will be generated.
- public function generate_captcha(){
- if(file_exists(FCPATH."assets/captcha/".$this->session->userdata['img']))
- unlink(FCPATH."assets/captcha/".$this->session->userdata['img']);
- $this->load->model('mcaptcha');
- $this->session->unset_userdata('cpt');
- $this->session->unset_userdata('img');
- $captcha = $this->mcaptcha->setCaptcha();
- echo json_encode(array('Mstatus'=>'success','Cmessage'=>$captcha,'msg' => validation_errors()));
- }
No comments:
Post a Comment
If you have any doubt let me know