Thursday, January 27, 2011

php example

UserValidation

<?php


class UserValidation{


function validatefirstName($firstName){

$namePattern="/^[a-zA-Z][a-zA-Z]*$/";
     
if(strlen($firstName)==0){

return "First Name Should Contains Characters";

}
else if(preg_match($namePattern,$firstName)!=true){

return "First name can contain only characters";

}
else{
//valid firstName
return "";
}

}//validatefirstName




function validateFullName($fullName){

$fullNamePattern="/^[a-zA-Z][a-zA-Z\\s]*$/";
     
if(strlen($fullName)<5){

return "Full Name Should At least 5 charcters long";
}
else if(preg_match($fullNamePattern,$fullName)!=true){

return "Full name can contain only characters";
}
else{
//valid fullname
return "";
}

}//validateFullName




function validateAddress($address){

if(strlen($address)==0){

return "address is required";
}
else{

return "";
}

}//validateAddress




function validateEmail($email){

$emailPattern="/^[a-zA-Z][a-zA-Z0-9_.]*[@][a-zA-Z0-9][a-zA-Z0-9]*[.][a-zA-Z][a-zA-Z]*$/";
     
if(preg_match($emailPattern,$email)!=true){

return "Invalid Email address";

}
else{
//valid email
return "";
}

}//validateEmail




function validateAge($age){

$agePattern="/^[0-9]*$/";
     
if(preg_match($agePattern,$age)!=true){

return "Invalid Age";

}
else{
//valid age
return "";
}

}//validAge


function validateUsername($username){

$usernamePattern="/^[a-zA-Z][a-zA-Z0-9]*$/";
if(strlen($username)==0){

return "username is required";
}
else if(strlen($username)<10){

return "username should contain at least 10 characters";
}  
else if(strlen($username)>15){

return "username can contain only maximum 15 characters";

}   
else if(preg_match($usernamePattern,$username)!=true){

return "Invalid Username";

}
else{
//valid age
return "";
}

}//validateusername





function validatePasswordAndPasswordConfirmation($password,$passwordConfirmation){

if($passwordConfirmation==""){

return "white spaces are not allowed for the password";

}
else if($password!=$passwordConfirmation){

return "Password does not match with the password confirmation";

}
else{
return "";
}

}//validatePassword




}//class



?>

registerNewUserController
<?php
include "../model/validation/UserValidation.php";
//registerNewUserController


if(isset($_POST["isAjax"])){

//creating validation object
$userValidation=new UserValidation;

if(isset($_POST["username"])){

//echo "validate username";

$validationErrors=$userValidation->validateUserName(trim($_POST["username"]));

if(strlen($validationErrors)!=0){

//there are validation errors

echo $validationErrors;

}
}


if(isset($_POST["firstName"])){

//echo "validate firstName"; 

$validationErrors=$userValidation->validatefirstName(trim($_POST["firstName"]));

if(strlen($validationErrors)!=0){

//there are validation errors

echo $validationErrors;

}


}//firstName



if(isset($_POST["fullName"])){

//echo "validate fullName"; 

$validationErrors=$userValidation->validateFullName(trim($_POST["fullName"]));

if(strlen($validationErrors)!=0){

//there are validation errors

echo $validationErrors;

}


}//fullName



if(isset($_POST["address"])){

//echo "validate address"; 


$validationErrors=$userValidation->validateAddress(trim($_POST["address"]));

if(strlen($validationErrors)!=0){

//there are validation errors

echo $validationErrors;

}



}


if(isset($_POST["email"])){

//echo "validate email"; 

$validationErrors=$userValidation->validateEmail(trim($_POST["email"]));

if(strlen($validationErrors)!=0){

//there are validation errors

echo $validationErrors;

}


}


if(isset($_POST["age"])){

//echo "validate age"; 

$validationErrors=$userValidation->validateAge(trim($_POST["age"]));

if(strlen($validationErrors)!=0){

//there are validation errors

echo $validationErrors;

}
}



if(isset($_POST["passwordConf"]) && isset($_POST["password"])){

$password=trim($_POST["password"]);
$passwordConf=trim($_POST["passwordConf"]);

$validationErrors=$userValidation->validatePasswordAndPasswordConfirmation($password,$passwordConf);

if(strlen($validationErrors)!=0){

//there are validation errors

echo $validationErrors;

}

}


}//if outer
else if(isset($_POST["submit"])){

echo "Form submit request";


}
else{

echo "invalid request";

}

?>

validateRegistrationFormUsingAjax

<?php
include "../model/validation/UserValidation.php";
//ajax validation controller


if(isset($_POST["isAjax"])){

$userValidation=new UserValidation;


if(isset($_POST["username"])){

$validationErrors=$userValidation->validateUserName(trim($_POST["username"]));

if(strlen($validationErrors)!=0){

echo $validationErrors;
}
}


if(isset($_POST["firstName"])){

$validationErrors=$userValidation->validatefirstName(trim($_POST["firstName"]));

if(strlen($validationErrors)!=0){

echo $validationErrors;
}
}//firstName



if(isset($_POST["fullName"])){

$validationErrors=$userValidation->validateFullName(trim($_POST["fullName"]));

if(strlen($validationErrors)!=0){

echo $validationErrors;
}
}//fullName



if(isset($_POST["address"])){

$validationErrors=$userValidation->validateAddress(trim($_POST["address"]));

if(strlen($validationErrors)!=0){

echo $validationErrors;
}
}


if(isset($_POST["email"])){

$validationErrors=$userValidation->validateEmail(trim($_POST["email"]));

if(strlen($validationErrors)!=0){

echo $validationErrors;

}
}


if(isset($_POST["age"])){

$validationErrors=$userValidation->validateAge(trim($_POST["age"]));

if(strlen($validationErrors)!=0){

echo $validationErrors;
}
}



if(isset($_POST["passwordConf"]) && isset($_POST["password"])){

$password=trim($_POST["password"]);
$passwordConf=trim($_POST["passwordConf"]);

$validationErrors=$userValidation->validatePasswordAndPasswordConfirmation($password,$passwordConf);

if(strlen($validationErrors)!=0){

echo $validationErrors;
}
}

}//if outer



//ajax request is to validate all data before submiting the form
if(isset($_POST["isAllData"])){

$userValidation=new UserValidation;
//$userValidationError="<b> The following Error Appear in Your Form </b><br/>";
$userValidationError="";

if(isset($_POST["username"])){

$validationErrors=$userValidation->validateUserName(trim($_POST["username"]));

if(strlen($validationErrors)!=0){

$userValidationError=$userValidationError."".$validationErrors."<br/>";

}
}


if(isset($_POST["firstName"])){

$validationErrors=$userValidation->validatefirstName(trim($_POST["firstName"]));

if(strlen($validationErrors)!=0){

$userValidationError=$userValidationError."".$validationErrors."<br/>";
}
}//firstName



if(isset($_POST["fullName"])){

$validationErrors=$userValidation->validateFullName(trim($_POST["fullName"]));

if(strlen($validationErrors)!=0){

$userValidationError=$userValidationError."".$validationErrors."<br/>";
}
}//fullName



if(isset($_POST["address"])){

$validationErrors=$userValidation->validateAddress(trim($_POST["address"]));

if(strlen($validationErrors)!=0){

$userValidationError=$userValidationError."".$validationErrors."<br/>";
}
}


if(isset($_POST["email"])){

$validationErrors=$userValidation->validateEmail(trim($_POST["email"]));

if(strlen($validationErrors)!=0){

$userValidationError=$userValidationError."".$validationErrors."<br/>";
}
}



if(isset($_POST["passwordConf"]) && isset($_POST["password"])){

$password=trim($_POST["password"]);
$passwordConf=trim($_POST["passwordConf"]);

$validationErrors=$userValidation->validatePasswordAndPasswordConfirmation($password,$passwordConf);

if(strlen($validationErrors)!=0){

$userValidationError=$userValidationError."".$validationErrors."<br/>";
}
}

if(isset($_POST["age"])){

$validationErrors=$userValidation->validateAge(trim($_POST["age"]));

if(strlen($validationErrors)!=0){

$userValidationError=$userValidationError."".$validationErrors."<br/>";
}
}






if(strlen($userValidationError)!=0){

//there are validation errors
echo $userValidationError;


}
else{

//there no validation errors

echo "valid";

}

}


?>


view

<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
<script type="text/javascript">


function createXmlHttpObject(){
  var xmlhttp="";
  
if (window.XMLHttpRequest)
  {// code for IE7+, Firefox, Chrome, Opera, Safari
  xmlhttp=new XMLHttpRequest();
  }
else
  {// code for IE6, IE5
  xmlhttp=new ActiveXObject("Microsoft.XMLHTTP");
  }
  
  return xmlhttp;
}  


function sendAjaxHttpRequest(xmlhttp,url,parameterName,parameterValue){

var parameters=parameterName+"="+parameterValue+"&isAjax=true";
xmlhttp.open("POST",url,true);
xmlhttp.setRequestHeader("Content-type", "application/x-www-form-urlencoded");
xmlhttp.setRequestHeader("Content-length", parameters.length);
xmlhttp.setRequestHeader("Connection", "close");
xmlhttp.send(parameters);

}


function validateFormItem(elementID,elementValue,spanTagId){

if (elementValue.length==0)
  {
  document.getElementById(spanTagId).innerHTML="";
  return;
  }

xmlhttp=createXmlHttpObject();

xmlhttp.onreadystatechange=function()
  {
  if (xmlhttp.readyState==4 && xmlhttp.status==200)
    {
 document.getElementById("txtAllErrors").innerHTML="";
    document.getElementById(spanTagId).innerHTML=xmlhttp.responseText;
    }
  }

sendAjaxHttpRequest(xmlhttp,"../controller/validateRegistrationFormController.php",elementID,elementValue);

}


//password validation
function passwordValidation(passwordConf){
 
var password=(document.getElementById("password")).value;
 
 
 
if (passwordConf.length==0)
  {
  document.getElementById("txtPasswordConf").innerHTML="";
  return;
  }
 
xmlhttp=createXmlHttpObject();
 
xmlhttp.onreadystatechange=function()
  {
  if (xmlhttp.readyState==4 && xmlhttp.status==200)
    {
 document.getElementById("txtPasswordConf").innerHTML="";
    document.getElementById("txtPasswordConf").innerHTML=xmlhttp.responseText;
    }
  }
 
var parameters="password="+password+"&passwordConf="+passwordConf+"&isAjax=true";
xmlhttp.open("POST","../controller/validateRegistrationFormController.php",true);
xmlhttp.setRequestHeader("Content-type", "application/x-www-form-urlencoded");
xmlhttp.setRequestHeader("Content-length", parameters.length);
xmlhttp.setRequestHeader("Connection", "close");
xmlhttp.send(parameters);
 
 
}

</script>
</head>

<body>

<h2>User Registration form </h2>

<form method="POST" action="../controller/registerNewUserController.php" id="userRegistrationForm" name="userRegistrationForm">

UserName <input type="text" name="username" id="username" onChange="validateFormItem('username',this.value,'txtUsername')"/><p><span id="txtUsername"></span></p>

FirstName <input type="text" name="firstName" id="firstName" onChange="validateFormItem('firstName',this.value,'txtFirstName')"/><p><span id="txtFirstName"></span></p>

fullName <input type="text" name="fullName" id="fullName" onChange="validateFormItem('fullName',this.value,'txtFullName')"/><p><span id="txtFullName"></span></p>

Age <input type="text" name="age" id="age" onChange="validateFormItem('age',this.value,'txtAge')"/><p><span id="txtAge"></span></p>

Address <input type="text" name="address" id="address" onChange="validateFormItem('address',this.value,'txtAddress')"/><p><span id="txtAddress"></span></p>

Email <input type="text" name="email" id="email" onChange="validateFormItem('email',this.value,'txtEmail')"/><p><span id="txtEmail"></span></p>

password <input type="password" name="password" id="password" /><p><span id="txtPassword"></span></p>

password confirmation  <input type="password" name="passwordConf" id="passwordConf" onChange="passwordValidation(this.value)"/><p><span id="txtPasswordConf"> </span></p>

<input id="submit" type="submit" name="submit" value="Register" />

</form>


</body>
</html>

Monday, January 24, 2011

Ajax as a POST and GET http requests

the most commonly used two HTTP methods known as GET and POST can be used with Ajax. today i am going to show you how to use both GET and POST methods for retrieving/modifying  the data from the server side.  the most of the time, GET method is used to retrieve data from the server and POST method is used to modify or alter the data in the server. therefore it is good to know how to use both of these methods with Ajax for implementing your solution in most optimal and standard way. the below code can be placed inside the head tag of your webpage to make Ajax POST method request for the server side. In server side, the relevant Controller logic should be implemented to handle POST requests.

POST
<script type="text/javascript">
//this function is used to create the xmlHttp Object based on the bowser type
function createXmlHttpObject(){
  var xmlhttp="";
  
if (window.XMLHttpRequest)
  {// code for IE7+, Firefox, Chrome, Opera, Safari
  xmlhttp=new XMLHttpRequest();
  }
else
  {// code for IE6, IE5
  xmlhttp=new ActiveXObject("Microsoft.XMLHTTP");
  }
  
  return xmlhttp;
}  

//this function is used to make the httpajax request to the server side
function sendAjaxHttpRequest(xmlhttp,url,parameterName,parameterValue){
/* if you need you can send mutiple parameters. here i am sending only a single parameter for the server side.
   isAjax=true is a parameter which has been set by myself to provide support for the server side implemetation done by myself.
   it is not required to send this parameter ot make the ajax functionality works */
var parameters=parameterName+"="+parameterValue+"&isAjax=true";
xmlhttp.open("POST",url,true);
xmlhttp.setRequestHeader("Content-type", "application/x-www-form-urlencoded");
xmlhttp.setRequestHeader("Content-length", parameters.length);
xmlhttp.setRequestHeader("Connection", "close");
//finally we are sending the parameters to the server side as a POST request
xmlhttp.send(parameters);

}

/* this is the actual usage. both above methods have been used here 
this is practical usage :- <input type='text" id="firstName" name="firstName" onchange="validateForm('firstName',this.value,'txtFirstName')/> <p><span id="txtFirstName"> </span></p>
*/
function validateForm(elementName,elementValue,SpanTagId)
{

if (elementValue.length==0)
  {
  document.getElementById(SpanTagId).innerHTML="";
  return;
  }
// we have called above createXmlHttpObject method to create the xmlHttp Object
xmlhttp=createXmlHttpObject();

xmlhttp.onreadystatechange=function()
  {
  if (xmlhttp.readyState==4 && xmlhttp.status==200)
    {
    document.getElementById(SpanTagId).innerHTML=xmlhttp.responseText;
    }
  }
/* we have called above sendAjaxHttpRequest method to make the actual ajax called for the server side. the url should be changed as your wish.
  i have implemeted this method to send only a single parameter for the server side. if you need you can send multiple parametes. in such case,
  you are required to provide parameters as below. 
   param1=param1value&param2=param3Value&....etc
   */
sendAjaxHttpRequest(xmlhttp,"http://localhost/mvc/index.php/userAdministration/ajaxValidation",elementName,elementValue,SpanTagId);

}//validateUsername


the following code segment can be used in your webpage for making Ajax GET request for the server side controller. in such case, the server side controller logic should be implemented in a way to deal with HTTP GET requests.

GET

<script type="text/javascript">
 
function validateUsername(userNameRetrived)
{ 
if (userNameRetrived.length==0)
  {
  document.getElementById("txtHint").innerHTML=""; 
  return;
  }
 
if (window.XMLHttpRequest)
  {// code for IE7+, Firefox, Chrome, Opera, Safari
  xmlhttp=new XMLHttpRequest();
  }
 
else 
  {// code for IE6, IE5 
  xmlhttp=new ActiveXObject("Microsoft.XMLHTTP"); 
  }
 
xmlhttp.onreadystatechange=function() 
  { 
  if (xmlhttp.readyState==4 && xmlhttp.status==200) 
    { 
    document.getElementById("txtUserNameMessage").innerHTML=xmlhttp.responseText; 
    }
  }
 
xmlhttp.open("GET","validate_form_data.php?username="+userNameRetrived,true); 
xmlhttp.send();
}
</script>

Hope this will be useful for you :)

regards
Chathuranga Tennakoon
chathuranga.t@gmail.com

Saturday, January 15, 2011

Codeigniter full MVC User Registration example

1. create the following view vie files in the application/views directory of the codeigniter framework.


(1). index.php 
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
<meta http-equiv="Content-Type" content="text/html; charset=iso-8859-1" />
<title>Home Page</title>
</head>

<body>
<?php
$this->load->helper('url');
$this->load->model("UserService");

$userService=new UserService();

$userIDs=$userService->getAllRegisteredUsersIDs();

?>
<table>
<tr><td>username</td><td>Edit</td><td>Remove</td></tr>
<?php for($index=0;$index<sizeof($userIDs);$index++){ ?>
<tr>
<td>Username</td><td><a href="<?php echo base_url(); ?>userAdministration/editUserDetails/<?php echo $userIDs[$index]; ?>">Edit User </a></td>
<td><a href="<?php echo base_url(); ?>userAdministration/removeRegisteredUser/<?php echo $userIDs[$index]; ?>">Remove User </a></td>
</tr>
<?php
}
?>

<tr><td><a href="<?php echo base_url(); ?>userAdministration/register">Add New User </a></td></tr>
</table>
</body>
</html> 

2. userRegisterView.php
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
<style type="text/css">

.error_color{
color:#FF0000;
}
</style>
<script type="text/javascript">

function createXmlHttpObject(){
  var xmlhttp="";
  
if (window.XMLHttpRequest)
  {// code for IE7+, Firefox, Chrome, Opera, Safari
  xmlhttp=new XMLHttpRequest();
  }
else
  {// code for IE6, IE5
  xmlhttp=new ActiveXObject("Microsoft.XMLHTTP");
  }
  
  return xmlhttp;
}  


function sendAjaxHttpRequest(xmlhttp,url,parameterName,parameterValue){

var parameters=parameterName+"="+parameterValue+"&isAjax=true";
xmlhttp.open("POST",url,true);
xmlhttp.setRequestHeader("Content-type", "application/x-www-form-urlencoded");
xmlhttp.setRequestHeader("Content-length", parameters.length);
xmlhttp.setRequestHeader("Connection", "close");
xmlhttp.send(parameters);

}


function validateForm(elementName,elementValue,SpanTagId)
{

if (elementValue.length==0)
  {
  document.getElementById(SpanTagId).innerHTML="";
  return;
  }

xmlhttp=createXmlHttpObject();

xmlhttp.onreadystatechange=function()
  {
  if (xmlhttp.readyState==4 && xmlhttp.status==200)
    {
    document.getElementById(SpanTagId).innerHTML=xmlhttp.responseText;
    }
  }

sendAjaxHttpRequest(xmlhttp,"http://localhost/mvc/index.php/userAdministration/ajaxValidation",elementName,elementValue,SpanTagId);

}//validateUsername



function passwordValidation(passwordConf){

var password=(document.getElementById("password")).value;



if (passwordConf.length==0)
  {
  document.getElementById("txtPasswordConf").innerHTML="";
  return;
  }

xmlhttp=createXmlHttpObject();

xmlhttp.onreadystatechange=function()
  {
  if (xmlhttp.readyState==4 && xmlhttp.status==200)
    {
    document.getElementById("txtPasswordConf").innerHTML=xmlhttp.responseText;
    }
  }

var parameters="password="+password+"&passwordConf="+passwordConf+"&isAjax=true";
xmlhttp.open("POST","http://localhost/mvc/index.php/userAdministration/ajaxValidation",true);
xmlhttp.setRequestHeader("Content-type", "application/x-www-form-urlencoded");
xmlhttp.setRequestHeader("Content-length", parameters.length);
xmlhttp.setRequestHeader("Connection", "close");
xmlhttp.send(parameters);


}

</script>
<meta http-equiv="Content-Type" content="text/html; charset=iso-8859-1" />
<title>Home Page- Chathuranga Tennakoon</title>
</head>
<body>
<?php
$this->load->helper('form');
$this->load->library('form_validation');
$this->load->helper('url');


$this->form_validation->set_error_delimiters('<div class="error_color">', '</div>');

echo form_open(base_url().'userAdministration/register',array('method'=>'post','class'=>'registration_form_div'));
?>
<table>
  <tr>
    <td><label>Username </label>
    </td>
    <td><input type="text"  id="username" name="username" value="<?php echo set_value('username'); ?>" onchange="validateForm('username',this.value,'txtUsername')" />
    </td>
    <td><p><span id="txtUsername"> <?php echo form_error('username'); ?> </span></p></td>
  </tr>
  <tr>
    <td><label>First Name </label></td>
    <td><input type="text" id="firstName" name="firstName" value="<?php echo set_value('firstName'); ?>" onchange="validateForm('firstName',this.value,'txtFirstName')"/>
    </td>
    <td><p><span id="txtFirstName"> <?php echo form_error('firstName'); ?></span></p></td>
  </tr>
  <tr>
    <td><label>Last Name </label></td>
    <td><input type="text"  id="lastName" name="lastName" value="<?php echo set_value('lastName'); ?>" onchange="validateForm('lastName',this.value,'txtLastName')"/>
    </td>
    <td><p><span id="txtLastName"> <?php echo form_error('lastName'); ?> </span></p></td>
  </tr>
  <tr>
    <td><label>Password </label></td>
    <td><input id="password" type="password" name="password" value="<?php echo set_value('password'); ?>" />
    </td>
    <td><p><span id="txtPassword"><?php echo form_error('password'); ?></span></p></td>
  </tr>
  <tr>
    <td><label>password confirmation </label></td>
    <td><input type="password" id="passwordConfirmation" name="passwordConfirmation" value="<?php echo set_value('passwordConfirmation'); ?>" onchange="passwordValidation(this.value)"/>
    </td>
    <td><p><span id="txtPasswordConf"><?php echo form_error('passwordConfirmation'); ?></span></p></td>
  </tr>
  <tr>
    <td><label>Age </label></td>
    <td><input type="text" name="age" value="<?php echo set_value('age'); ?>" onchange="validateForm('age',this.value,'txtAge')"/>
    </td>
    <td><p><span id="txtAge"> <?php echo form_error('age'); ?> </span></p></td>
  </tr>
  <tr>
    <td><label>Address </label></td>
    <td><input type="text" name="address" value="<?php echo set_value('address'); ?>" onchange="validateForm('address',this.value,'txtAddress')"/>
    </td>
    <td><p><span id="txtAddress"><?php echo form_error('address'); ?></span></p></td>
  </tr>
  <tr>
    <td><label>Email </label></td>
    <td><input type="text" name="email" value="<?php echo set_value('email'); ?>" onchange="validateForm('email',this.value,'txtEmail')"/>
    </td>
    <td><p><span id="txtEmail"><?php echo form_error('email'); ?></span></p></td>
  </tr>
  <tr>
    <td><label>Telephone </label></td>
    <td><input type="text" name="telephone" value="<?php echo set_value('telephone'); ?>" onchange="validateForm('telephone',this.value,'txtTelephone')" />
    </td>
    <td><p><span id="txtTelephone"><?php echo form_error('telephone'); ?> </span></p></td>
  </tr>
</table>
<input type="submit" value="Register" name="registerUser" class="registration_textfield" />
<?php
echo  form_close(); 
?>
</body>
</html>

3. userEditView.php
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
<style type="text/css">

.error_color{
color:#FF0000;
}
</style>
<script type="text/javascript">

function createXmlHttpObject(){
  var xmlhttp="";
  
if (window.XMLHttpRequest)
  {// code for IE7+, Firefox, Chrome, Opera, Safari
  xmlhttp=new XMLHttpRequest();
  }
else
  {// code for IE6, IE5
  xmlhttp=new ActiveXObject("Microsoft.XMLHTTP");
  }
  
  return xmlhttp;
}  


function sendAjaxHttpRequest(xmlhttp,url,parameterName,parameterValue){

var parameters=parameterName+"="+parameterValue+"&isAjax=true";
xmlhttp.open("POST",url,true);
xmlhttp.setRequestHeader("Content-type", "application/x-www-form-urlencoded");
xmlhttp.setRequestHeader("Content-length", parameters.length);
xmlhttp.setRequestHeader("Connection", "close");
xmlhttp.send(parameters);

}


function validateForm(elementName,elementValue,SpanTagId)
{

if (elementValue.length==0)
  {
  document.getElementById(SpanTagId).innerHTML="";
  return;
  }

xmlhttp=createXmlHttpObject();

xmlhttp.onreadystatechange=function()
  {
  if (xmlhttp.readyState==4 && xmlhttp.status==200)
    {
    document.getElementById(SpanTagId).innerHTML=xmlhttp.responseText;
    }
  }

sendAjaxHttpRequest(xmlhttp,"http://localhost/mvc/index.php/userAdministration/ajaxValidation",elementName,elementValue,SpanTagId);

}//validateUsername



function passwordValidation(passwordConf){

var password=(document.getElementById("password")).value;



if (passwordConf.length==0)
  {
  document.getElementById("txtPasswordConf").innerHTML="";
  return;
  }

xmlhttp=createXmlHttpObject();

xmlhttp.onreadystatechange=function()
  {
  if (xmlhttp.readyState==4 && xmlhttp.status==200)
    {
    document.getElementById("txtPasswordConf").innerHTML=xmlhttp.responseText;
    }
  }

var parameters="password="+password+"&passwordConf="+passwordConf+"&isAjax=true";
xmlhttp.open("POST","http://localhost/mvc/index.php/userAdministration/ajaxValidation",true);
xmlhttp.setRequestHeader("Content-type", "application/x-www-form-urlencoded");
xmlhttp.setRequestHeader("Content-length", parameters.length);
xmlhttp.setRequestHeader("Connection", "close");
xmlhttp.send(parameters);


}

</script>
<meta http-equiv="Content-Type" content="text/html; charset=iso-8859-1" />
<title>Home Page- Chathuranga Tennakoon</title>
</head>
<body>
<?php
$this->load->helper('form');
$this->load->library('form_validation');
$this->load->helper('url');

$this->form_validation->set_error_delimiters('<div class="error_color">', '</div>');

echo form_open(base_url().'userAdministration/editUser',array('method'=>'post','class'=>'registration_form_div'));
?>
<table>
  <tr>
    <td><label>Username </label></td>
    <td><input type="text" name="username" value="<?php if(isset($username)){ echo $username; }else{ echo set_value('username'); } ?>" onchange="validateForm('username',this.value,'txtUsername')" />
      <input type="hidden" value="<?php echo $userID; ?>" name="userID" id="userID" />
    </td>
    <td><p><span id="txtUsername"> <?php echo form_error('username'); ?> </span></p></td>
  </tr>
  
  <tr>
    <td><label>First Name </label></td>
    <td><input type="text" name="firstName" value="<?php if(isset($firstName)){ echo $firstName; }else{ echo set_value('firstName'); } ?>" onchange="validateForm('firstName',this.value,'txtFirstName')" />
    </td>
    <td><p><span id="txtFirstName"> <?php echo form_error('firstName'); ?> </span></p></td>
  </tr>
  
  <tr>
    <td><label>Last Name </label></td>
    <td><input type="text" name="lastName" value="<?php if(isset($lastName)){ echo $lastName; }else{ echo set_value('lastName'); } ?>" onchange="validateForm('lastName',this.value,'txtLastName')"  />
    </td>
    <td><p><span id="txtLastName"> <?php echo form_error('lastName'); ?> </span></p></td>
  </tr>
  
  <tr>
    <td><label>Password </label></td>
    <td><input type="password" name="password" value="<?php if(isset($password)){ echo $password; }else{ echo set_value('password'); } ?>"/>
    </td>
    <td><?php echo form_error('password'); ?> </td>
  </tr>
  
  <tr>
    <td><label>password confirmation </label></td>
    <td><input type="password" name="passwordConfirmation" value="<?php if(isset($password)){ echo $password; }else{ echo set_value('passwordConfirmation'); } ?>" onchange="passwordValidation(this.value)" />
    </td>
    <td><p><span id="txtPasswordConf"> <?php echo form_error('passwordConfirmation'); ?> </span></p></td>
  </tr>
  
  <tr>
    <td><label>Age </label></td>
    <td><input type="text" name="age" value="<?php if(isset($age)){ echo $age; }else{ echo set_value('age'); } ?>" onchange="validateForm('age',this.value,'txtAge')" />
    </td>
    <td><p><span id="txtAge"> <?php echo form_error('age'); ?> </span></p></td>
  </tr>
  
  <tr>
    <td><label>Address </label></td>
    <td><input type="text" name="address" value="<?php if(isset($address)){ echo $address; }else{ echo set_value('address'); } ?>" onchange="validateForm('address',this.value,'txtAddress')" />
    </td>
    <td><p><span id="txtAddress"> <?php echo form_error('address'); ?> </span></p></td>
  </tr>
  <tr>
    <td><label>Email </label></td>
    <td><input type="text" name="email" value="<?php if(isset($email)){ echo $email; }else{ echo set_value('email'); } ?>" onchange="validateForm('email',this.value,'txtEmail')" />
    </td>
    <td><p><span id="txtEmail"> <?php echo form_error('email'); ?> </span></p></td>
  </tr>
  
  <tr>
    <td><label>Telephone </label></td>
    <td><input type="text" name="telephone" value="<?php if(isset($telephone)){ echo $telephone; }else{ echo set_value('telephone'); } ?>" onchange="validateForm('telephone',this.value,'txtTelephone')" />
    </td>
    <td><p><span id="txtTelephone"> <?php echo form_error('telephone'); ?> </span></p></td>
  </tr>
  
</table>
<input type="submit" value="Register" name="registerUser" class="registration_textfield" />
<?php
echo  form_close(); 
?>
</body>
</html>

2. Models

(1) UserModel.php
<?php
class UserModel extends CI_Model {

     var $userID='';
     var $username = '';
     var $password = '';
     var $email = '';
     var $firstName = '';
     var $address = '';
     var $age = '';
     var $telephone = '';
    

    function __construct()
    {
        // Call the Model constructor
        parent::__construct();
    }
    
    
    function setUserID($userIDprovided){
    
        $this->userID=$userIDprovided;
    }
    
    function getUserID(){
    
    return $this->userID;
    }
    
    function getUserName(){
    
    return $this->username;
    }
    
    function setUserName($usernameProvided){
    
    $this->username=$usernameProvided;
    
    }
    
    
    function getFirstName(){
    
    return $this->firstName;
    }
    
    function setFirstName($fisrtNameProvided){
    
    $this->firstName=$fisrtNameProvided;
    
    }
    
    
    function getLastName(){
    
    return $this->lastName;
    }
            
    function setLastName($lastNameProvided){
    
     $this->lastName=$lastNameProvided;
    
    }
    
    
    function getEmail(){
    
    return $this->email;
    }
    
    function setEmail($emailProvided){
    
    $this->email=$emailProvided;
    
    }    
    
    
    function getAge(){
    
    return $this->age;
    }
    
    function setAge($ageProvided){
    
    $this->age=$ageProvided;
    
    }
    
    
    function getTelephone(){
    
    return $this->telephone;
    }
    
    function setTelephone($telephoneProvided){
    
    $this->telephone=$telephoneProvided;
    
    }
    
    
    function getAddress(){
    
    return $this->address;
    }
    
    function setAddress($addressProvided){
    
    $this->address=$addressProvided;
    
    }
    

    function getPassword(){
    
    return $this->password;
    }
    
    function setPassword($passwordProvided){
    
    $this->password=$passwordProvided;
    
    }
    
    
        
}//class
        
?>    
  

(2.) EmailClass.php
<?php
class EmailClass extends CI_Model {

     var $emailUsername="xxxxxxxt@gmail.com";
     var $emailPassword="yourPassword";
     var $emailHost="ssl://smtp.googlemail.com";
     var $emailProtocol="smtp";
     var $emailPort="465";
     var $emaiType="html";
    
    function __construct()
    {
        // Call the Model constructor
        parent::__construct();
        //$this->load->helper("url");
    }
    
    
function sendEmail($emailFrom,$emailTo,$subject,$message){
    
 $config = Array(
  'protocol' => $this->emailProtocol,
  'smtp_host' => $this->emailHost,
  'smtp_port' => $this->emailPort,
  'smtp_user' => $this->emailUsername, // change it to yours
  'smtp_pass' => $this->emailPassword, // change it to yours
  'mailtype' => $this->emaiType,
  'charset' => 'iso-8859-1',
  'wordwrap' => TRUE
);
  $this->load->library('email', $config);
  $this->email->set_newline("\r\n");
  $this->email->from($emailFrom); // change it to yours
  $this->email->to($emailTo); // change it to yours
  $this->email->subject($subject);
  $this->email->message($message);

  if($this->email->send())
  {

   return true;

  }
  else
  {
   show_error($this->email->print_debugger());
   
   return false;
  }
  
    
}
    
        
}//class
        
?>    


(3.)UserService.php
<?php
class UserService extends CI_Model {


   function __construct()
    {
        // Call the Model constructor
        parent::__construct();
        $this->load->database();    

    }
    
    
     function createNewUser($user){
        
            
      $username=$user->getUserName();
      $firstName=$user->getFirstName();
      $lastName=$user->getLastName();
      $email=$user->getEmail();
      $telephone=$user->getTelephone();
      $age=$user->getAge();
      $password=$user->getPassword();
      $address=$user->getAddress();

      
       $insertStatus=$this->db->insert('user',array('username'=>$username ,'firstName'=>$firstName ,'lastName'=>$lastName ,'email'=>$email ,'age'=>$age ,'password'=>$password ,'address'=>$address      ,'telephone'=>$telephone)); 
       
       if($insertStatus){
       
       return true;
       }
       else{
       
       return false;
       
       }
    
    }//createNewUser
    
    
    
    
    function editUserDetails($user){
    
    
      $username=$user->getUserName();
      $firstName=$user->getFirstName();
      $lastName=$user->getLastName();
      $email=$user->getEmail();
      $telephone=$user->getTelephone();
      $age=$user->getAge();
      $password=$user->getPassword();
      $address=$user->getAddress();

        $this->db->where('userID', $user->getUserID());
       $updatedStatus=$this->db->update('user',array('username'=>$username ,'firstName'=>$firstName ,'lastName'=>$lastName ,'email'=>$email ,'age'=>$age ,'password'=>$password ,'address'=>$address,'telephone'=>$telephone)); 
       
       if($updatedStatus){
       
       return true;
       }
       else{
       
       return false;
       
       }
    
    
    
    
    }//editUserDetails
    
    
    
    
    function getAllRegisteredUsersIDs(){
        
    $this->db->select('userID');
    $query = $this->db->get('user');
    $selectedDataArray=array();
    
    $i=0;
    
    foreach ($query->result() as $row){
    
    $selectedDataArray[$i]=$row->userID;
    $i++;
    }
    
     return $selectedDataArray;
    
    }//getAllRegisteredUsersIDs
    
    
    
    
    
    function removeRegisteredUser($user){
        
    $this->db->where('userID', $user->getUserID());
    $this->db->delete('user'); 
    
    }//removeRegisteredUser
    
    
    
    
    function getSelectedUserDetails($user){
        
        $query = $this->db->get_where('user', array('userID' => $user->getUserID()));
    
        $selectedData="";
        
        foreach ($query->result() as $row){

         $selectedData=array("username"=>$row->username,"firstName"=>$row->firstName,"lastName"=>$row->lastName,"password"=>$row->password,"age"=>$row->age,"telephone"=>$row->telephone,"address"=>$row->address,"email"=>$row->email,"userID"=>$row->userID);
        
        }
        
        return $selectedData;
        
    }//getSelectedUserDetails
    
    
    
    function isUserNamealreadyRegisterd($user){
        
    $username=$user->getUserName();
    
    $query = $this->db->get_where('user', array('username' => $username));
    
    if($query->num_rows()==0){
    
    return false;
    
    }
    else{
    
    return  true;
    }
      
    }//function
    
    
   }//class
    
    
    
?>
 
3.  Controller

UserAdministration.php
<?php

class userAdministration extends CI_Controller {


    public function index()
    {
        echo 'welcome to userAdministration Controller';
    }
    
    
    public function register(){
    
        //echo "registering new user";
        $this->load->helper(array('form', 'url'));
        $this->load->library('form_validation');
    
        $this->form_validation->set_rules('username', 'Username', 'required|min_length[5]|max_length[12]|xss_clean|trim|alpha_numeric');
        $this->form_validation->set_rules('password', 'Password', 'required|xss_clean|trim');
        $this->form_validation->set_rules('passwordConfirmation', 'Password Confirmation', 'required|matches[password]|xss_clean|trim');
        $this->form_validation->set_rules('age', 'Age', 'required|xss_clean|trim|integer');
        $this->form_validation->set_rules('email', 'Email', 'required|valid_email|xss_clean|trim');
        $this->form_validation->set_rules('firstName', 'First Name', 'required|xss_clean|trim|alpha');
        $this->form_validation->set_rules('lastName', 'Last Name', 'required|xss_clean|trim|alpha');
        $this->form_validation->set_rules('address', 'Address', 'required|xss_clean|trim');
        $this->form_validation->set_rules('telephone', 'Telephone', 'required|xss_clean|trim|exact_length[10]|integer');



        if ($this->form_validation->run() == FALSE){
        
            $this->load->view('userRegisterView');
        
        }
        else
        {
             //loading the required model and service classes
             $this->load->model("UserModel");
             $this->load->model("UserService");
             $this->load->model("EmailClass");

            
            $userModel=new UserModel();    
            $userService=new UserService();
            
            $userModel->setUserName($this->input->post('username', TRUE));
            $userModel->setFirstName($this->input->post('firstName', TRUE));
            $userModel->setLastName($this->input->post('lastName', TRUE));
            $userModel->setPassword($this->input->post('password', TRUE));
            $userModel->setAge($this->input->post('age', TRUE));
            $userModel->setAddress($this->input->post('address', TRUE));
            $userModel->setTelephone($this->input->post('telephone', TRUE));
            $userModel->setEmail($this->input->post('email', TRUE));
                                                
            $dbInserted=$userService->createNewUser($userModel);

            
            if($dbInserted){
            
                //echo "registration email should be sent";
        
              $emailClass=new EmailClass();
            
              $emailSentStatus=$emailClass->sendEmail("chathuranga.t@gmail.com","chathuranga.t@gmail.com","new user registration","chathurangat.blogspot.com");
            
             if($emailSentStatus){
            
             redirect(base_url()); //with success message
            
             }
             else{
            
             redirect(base_url()); //with error message
             }    
            
            }//if
                                    
        }//else            
    }//register    
    
    
    function removeRegisteredUser($userID){
    
    
    //echo "request for remeving user with  userID ".$userID;
             $this->load->model("UserModel");
             $this->load->model("UserService");
             $this->load->helper("url");

            $userModel=new UserModel();    
            $userService=new UserService();
      
            $userModel->setUserID($userID);
            
            $userService->removeRegisteredUser($userModel);
            
            redirect(base_url()); //with error message
            
         
    }//removeRegisteredUser
    
    
    
    function editUserDetails($userID){
    
    //echo "request for editing user with userID ".$userID;
    
             $this->load->helper(array('form', 'url'));
             $this->load->library('form_validation');        
             $this->load->model("UserModel");
             $this->load->model("UserService");
             $this->load->helper("url");

            $userModel=new UserModel();    
            $userService=new UserService();
      
            $userModel->setUserID($userID);
            
            $retievedUserData=$userService->getSelectedUserDetails($userModel);
            
            $this->load->view("userEditView",$retievedUserData);
            
    
    }//display Edit user details from
    
    
    
    
    public function editUser(){
    
        //echo "registering new user";
        $this->load->helper(array('form', 'url'));
        $this->load->library('form_validation');
    
        $this->form_validation->set_rules('username', 'Username', 'required|min_length[5]|max_length[12]|xss_clean|trim|alpha_numeric');
        $this->form_validation->set_rules('password', 'Password', 'required|xss_clean|trim');
        $this->form_validation->set_rules('passwordConfirmation', 'Password Confirmation', 'required|matches[password]|xss_clean|trim');
        $this->form_validation->set_rules('age', 'Age', 'required|xss_clean|trim|integer');
        $this->form_validation->set_rules('email', 'Email', 'required|valid_email|xss_clean|trim');
        $this->form_validation->set_rules('firstName', 'First Name', 'required|xss_clean|trim|alpha');
        $this->form_validation->set_rules('lastName', 'Last Name', 'required|xss_clean|trim|alpha');
        $this->form_validation->set_rules('address', 'Address', 'required|xss_clean|trim');
        $this->form_validation->set_rules('telephone', 'Telephone', 'required|xss_clean|trim|exact_length[10]|integer');



        if ($this->form_validation->run() == FALSE){
        
            $this->load->view('userRegisterView');
        
        }
        else
        {
             //loading the required model and service classes
             $this->load->model("UserModel");
             $this->load->model("UserService");

            
            $userModel=new UserModel();    
            $userService=new UserService();
            
            $userModel->setUserName($this->input->post('username', TRUE));
            $userModel->setFirstName($this->input->post('firstName', TRUE));
            $userModel->setLastName($this->input->post('lastName', TRUE));
            $userModel->setPassword($this->input->post('password', TRUE));
            $userModel->setAge($this->input->post('age', TRUE));
            $userModel->setAddress($this->input->post('address', TRUE));
            $userModel->setTelephone($this->input->post('telephone', TRUE));
            $userModel->setEmail($this->input->post('email', TRUE));
            $userModel->setUserID($this->input->post('userID', TRUE));    
                                            
            $dbCommited=$userService->editUserDetails($userModel);
            
            
            if($dbCommited){
            
             redirect(base_url()); //with success message
            
             }
             else{
            
             redirect(base_url()); //with error message
             }    
            
                                    
        }//else            
    }//editUser    
    
    
    
    function ajaxValidation(){
    
    $this->load->model("UserModel");
    $this->load->model("UserService");

      $userModel=new UserModel();    
      $userService=new UserService();
    //validating user input using ajax
    
     $this->load->helper(array('form', 'url'));
     $this->load->library('form_validation');
    
    $username=$this->input->post('username');
    $email=$this->input->post('email');
    $address=$this->input->post('address');
    $telephone=$this->input->post('telephone');
    $age=$this->input->post('age');
    $lastName=$this->input->post('lastName');
    $firstName=$this->input->post('firstName');
    $password=$this->input->post('password');    
    $passwordConf=$this->input->post('passwordConf');        
        
    //username validate                
    if(isset($username) && $username!=""){
    
    $this->form_validation->set_rules('username', 'Username', 'required|min_length[5]|max_length[12]|xss_clean|trim|alpha');

    if($this->form_validation->run() == FALSE){
    
    echo validation_errors();
    
    }
    else{
    
    $userService=new UserService();
    $userModel=new UserModel();
    
    $userModel->setUserName($username);
    
    $userStatus=$userService->isUserNamealreadyRegisterd($userModel);
    
    if($userStatus){
    
    echo "Username is already taken";
    
    }
    else{
    
    echo "Username is avaialable";
    
    }
    }
    }//username
    
    
    
    //validating email
    
    if(isset($email) && $email!="" ){
    
     $this->form_validation->set_rules('email', 'Email', 'required|valid_email|xss_clean|trim');

    if($this->form_validation->run() == FALSE){
    
    echo validation_errors();
    
    }
    
    }//email
    
    
      //validating address
    
        if(isset($address) && $address!="" ){
    
        $this->form_validation->set_rules('address', 'Address', 'required|xss_clean|trim');

        if($this->form_validation->run() == FALSE){
    
        echo validation_errors();
    
       }

       }//address
    
    
    
        
    
       //validating age
    
       if(isset($age) && $age!="" ){
    
         $this->form_validation->set_rules('age', 'Age', 'required|xss_clean|trim|integer');

        if($this->form_validation->run() == FALSE){
    
        echo validation_errors();
    
         }
                 
        }//age
    
    
        //validating telephone
    
        if(isset($telephone) && $telephone!="" ){
    
        $this->form_validation->set_rules('telephone', 'Telephone', 'required|xss_clean|trim|exact_length[10]|integer');

        if($this->form_validation->run() == FALSE){
    
        echo validation_errors();
    
         }
                 
        }//telephone
    
    
       //validating first name
    
        if(isset($firstName) && $firstName!="" ){
    
          $this->form_validation->set_rules('firstName', 'First Name', 'required|xss_clean|trim|alpha');

        if($this->form_validation->run() == FALSE){
    
          echo validation_errors();
    
         }
                 
        }//firstName
    
    
    
        //validating last name
    
        if(isset($lastName) && $lastName!="" ){
    
        $this->form_validation->set_rules('lastName', 'Last Name', 'required|xss_clean|trim|alpha');

        if($this->form_validation->run() == FALSE){
    
         echo validation_errors();
    
         }
                 
        }//lastName
        
        
        
        
        if(isset($password) && $password!="" && isset($passwordConf) && $passwordConf!="" ){
        
    
        if($password!=$passwordConf){
        
        echo  "Password and Password Confirmation field does not match";
                
        }

        }//password
    
    
    
    }//ajaxValidation
    
}//class

?> 




Configuration in application/config/database.php
$db['default']['hostname'] = 'localhost';
$db['default']['username'] = 'root';
$db['default']['password'] = '';
$db['default']['database'] = 'test_mvc';
$db['default']['dbdriver'] = 'mysql';


My SQL Table Structure
CREATE TABLE IF NOT EXISTS `user` (
  `userID` int(11) NOT NULL auto_increment,
  `username` varchar(100) NOT NULL,
  `password` varchar(100) NOT NULL,
  `firstName` varchar(100) NOT NULL,
  `lastName` varchar(100) NOT NULL,
  `address` varchar(500) NOT NULL,
  `email` varchar(100) NOT NULL,
  `age` int(11) NOT NULL,
  `telephone` varchar(100) NOT NULL,
  PRIMARY KEY  (`userID`),
  UNIQUE KEY `username` (`username`)
) 





regards
Chathuranga Tennakoon
chathuranga.t@gmail.com