September 16, 2012

September 16, 2012
1

This tutorial will helps you to check live availability of username or email using Ajax in Codeigniter. Using this tutorial you can also understand how can we send a jQuery Ajax request to server living in Codeigniter.

In your "view", where you have created form include jQuery library and put the below code there.

In header section:

$(document).ready(function() {     
 /// make loader hidden in start     
 $('#Loading').hide();            
 $('#email').blur(function(){   
 var a = $("#email").val();   
 var filter = /^[a-zA-Z0-9]+[a-zA-Z0-9_.-]+[a-zA-Z0-9_-]+@[a-zA-Z0-9]+[a-zA-Z0-9.-]+[a-zA-Z0-9]+.[a-z]{2,4}$/;        
 // check if email is valid   
 if(filter.test(a)){                 
  // show loader     
  $('#Loading').show();    
  $.post("<?php echo base_url()?>controller_name/check_email_availablity", {     
  email: $('#email').val()    
 },
 function(response){                         
  //#emailInfo is a span which will show you message     
  $('#Loading').hide();     
  setTimeout("finishAjax('Loading', '"+escape(response)+"')", 400);    
 });    
 return false;   
} 
}); 
function finishAjax(id, response){   
 $('#'+id).html(unescape(response));   
 $('#'+id).fadeIn(); 
}

In body section of your form:

<div>   
 <label>E-mail</label>   
 <input id="email" name="email" type="text" value=""  />   
 <span id="Loading"><img src="loader.gif" alt="Ajax Indicator" /></span>  
</div>

In "controller" add this function:

function check_email_availablity()  {   
 $this->load->model('My_model');   
 $get_result = $this->My_model->check_email_availablity();      
 if(!$get_result )   
  echo '<span >Email already in use. </span>';   
 else   
  echo '<span >Email Available</span>'; 
}

Suppose you have a model called my_model.php and a table tbl_members or what ever you named. This table should have a field named "email" of type varchar [200].

Add this function:

function check_email_availablity()  {         
 $email = trim($this->input->post('email'));   
 $email = strtolower($email);       
 $query = $this->db->query('SELECT * FROM tbl_members where email="'.$email.'"');      
 if($query->num_rows() > 0)   
  return false;   
 else 
  return true; 
}

Thats it, this function will return a message against email field that whether it is available or not. This is not for only email, you can use it to check any field. Also this is client side check so you also need to use this model function in server side so that email can also be verified when form has been submitted with disabling javascript .

1 comments:

  1. Hey, I want to use it in Cakephp, Pls give a nice tutorial,Thankks.

    ReplyDelete