Friday, September 5, 2014

Search Function with PHP-Codeigniter

   Working with CodeIgniter as a developer is a great experience. Including AJAX inside CodeIgniter is a pleasure. CodeIgniter + AJAX offers a great user-experience if they are combine in a harmonious way.
 
   Providing a search function that searches your Web pages is a design strategy that offers users a way to find content. Users can locate content by searching for specific words or phrases, without needing to understand or navigate through the structure of the Web site. This can be a quicker or easier way to find content, particularly on large sites.


 Let’s start!




View


<head>
<script type="text/javascript" src=<?php echo base_url('assets/jquery-ui/js/jquery-1.10.2.js'); ?>></script>
<script type="text/javascript" src=<?php echo base_url('assets/jquery-ui/js/jquery-ui-1.10.4.custom.min.js'); ?>></script>
<!-- <script type="text/javascript" language="javascript" src="<?php echo base_url(); ?>js/jquery.js"></script>-->
<script type="text/javascript" src=<?php echo base_url('assets/js/json2.js'); ?>></script>
<script>

function check_(){
if($("#search_prj").is(':checked')){
if($("#search_usr").is(':checked'))
$("#vall").val('3');
else
$("#vall").val('1');
}
else{
if($("#search_usr").is(':checked'))
$("#vall").val('2');
else
$("#vall").val('0');
}
}
$(document).ready(function(){
$("#search_prj").change(function(){
check_();
});

$("#search_usr").change(function(){
check_();
});

$("#search").keyup(function(){
if($("#search").val().length>3){
$.ajax({
type: "post",
url: "search",
cache: false,
data:'search='+$("#search").val() +'&v='+$("#vall").val(),

success: function(response){
$('#finalResult').html("");
var obj = JSON.parse(response);
if(obj.length>0){
try{
var items=[];
$.each(obj, function(i,val){
items.push($('<li>').text(val.name));

});
$('#finalResult').append.apply($('#finalResult'), items);
}catch(e) {
alert('Exception while request..');
}
}else{
$('#finalResult').html($('<li/>').text("No Data Found"));
}

},
error: function(){
alert('Error while request..');
}
});
}
return false;
});
});
</script>
</head>
<body>
<?php echo form_open('search/getDetails'); ?>
<center>
<table border="0">
<tr>
<td>search </td>
<div id="container">
<td> <input type="text" id="search" name="keyword" autocomplete="off"> &nbsp;<ul id="finalResult"></ul></td>
</div>
<td> <button type="submit" class="btn btn-default btn-lg">
<span class="glyphicon glyphicon-search"></span>
</button> </td>
</tr>
<tr>
<td><input type="radio" name="search_val" id="search_prj" value="1">Projects </input></td>
</tr>
<tr>
<td><input type="radio" name="search_val" id="search_usr" value="2">Users </input>
         <input type="text" hidden value="0" id ="vall"/> </td>
</tr>
</table>
</center>
<?php echo form_close(); ?>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.0/jquery.min.js"></script>
<script type="text/javascript" src=<?php echo base_url('assets/js/bootstrap.min.js'); ?>></script>
</body>
</html>

   This code gives the interface of the search function. The ajax code written in the head section gives the auto-complete of our search function. If I give a breif description of the ajax code...

  First we should create a textbox and make it hidden so that we can check if the radio buttons are selected. vall is the id of this hidden textbox. If the Users radio button is clicked value of the hidden textbox will be 1 where as if the Projects  radio button is clicked value of the hidden textbox will be 2. Then it checks if the radio button is actually checkd by the check() function.
  In the keyup function, that is when the key is released it checks if the value of the search textbox is greater than 3 in length. in the success function the serch results will be listed down as in the error function an alert will be shown.


Model

<?php
class model_search extends CI_Model {

function getEmployee($search, $v){
if($v=="1"){
$this->db->select("name");
$whereCondition =array('name' =>$search);
$this->db->where($whereCondition);
$this->db->from('project');
$query = $this->db->get();
return $query->result();
}
else if($v=="2"){
$this->db->select("username as name");
$whereCondition =array('fName' =>$search);
$this->db->where($whereCondition);
$this->db->from('users');
$query = $this->db->get();
return $query->result();
}
else if($v=="3"){
return null;
}
}
}
?>


Here the value of the hidden textbox is checked. If the value=1 the given query will be executed where all projects will be selected. If value=2 is selected all usernames will be be selected else it will return null.


Controller

<?php
class search extends CI_Controller {
   
    public function __construct(){
            parent::__construct();

            $this->load->helper('url');
            $this->load->helper('html');
            session_start();
    }

    public function index(){
        $this->load->model('model_search');
        if(!(isset($_POST['search']))){
            $this->load->view('view_header');
            $this->load->view('view_search');
        }
        else{
            $v = $this->input->post('v');
            $search=  $this->input->post('search');
            $query = $this->model_search->getEmployee($search, $v);
             echo json_encode ($query);
        }
    }

    public function getDetails()
    {
        $this->load->model('model_search');
        $search_q=  $this->input->post('keyword');
        $this->load->view('view_header');
        $this->load->model('model_getSearchValue');

        $search_val=$this->input->post('search_val');
     
        if($search_val=='1'){
            $data1['result1']=$this->model_getSearchValue->getProjects($search_q)->result();
            $this->load->view('view_searchProjects',$data1);
        }
        if($search_val=='2'){
            $data2['result2']=$this->model_getSearchValue->getUsers($search_q)->result();
            $this->load->view('view_searchUsers',$data2);

        }
    }
}
?>

This is the controller which calls all models and views created.In the index function if there is any value in the searchbox it will call the abouve created model's functions. The getDetails function is where you load the interfaces when you click on the search button. search_val is the name we have given for  post value of the 2 radio buttons we have added. If the id of the radio button is 1 it will search for the given project name where as if the id is 2 it will view the user we want to search.

No comments:

Post a Comment