September 16, 2012

September 16, 2012

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     
 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   
  // show loader     
  $.post("<?php echo base_url()?>controller_name/check_email_availablity", {     
  email: $('#email').val()    
  //#emailInfo is a span which will show you message     
  setTimeout("finishAjax('Loading', '"+escape(response)+"')", 400);    
 return false;   
function finishAjax(id, response){   

In body section of your form:

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

In "controller" add this function:

function check_email_availablity()  {   
 $get_result = $this->My_model->check_email_availablity();      
 if(!$get_result )   
  echo '<span >Email already in use. </span>';   
  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;   
  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. Hey, I want to use it in Cakephp, Pls give a nice tutorial,Thankks.