Monday, 11 May 2015

Ajax captcha using codeigniter php bootstrapvalidator

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

No comments:

Post a Comment

If you have any doubt let me know