How to create a Codeigniter Auto Complete Search

// js code after document is ready
// Search autocomplete
$("#swSearch").autocomplete({
	minLength: 1,
	source: function(req, add){
		$.ajax({
			url: '/search', //Controller where search is performed
			dataType: 'json',
			type: 'POST',
			data: req,
			success: function(data){
				if(data.response =='true'){
				   add(data.message);
				}
			}
		});
	}
});





// Controller search function

$keyword = $this->input->post('term');

$data['response'] = 'false'; //Set default response

$query = $this->Mprofile->sw_search($keyword); //Model DB search

if($query->num_rows() > 0){
   $data['response'] = 'true'; //Set response
   $data['message'] = array(); //Create array
   foreach($query->result() as $row){
	  $data['message'][] = array('label'=> $row->friendly_name, 'value'=> $row->friendly_name); //Add a row to array
   }
}
echo json_encode($data);



// Simple model example

public function sw_search($keyword)
    {
        $this->db->select('id, friendly_name');
        $this->db->from('business_category');
        $this->db->where('suppress', 0);
        $this->db->like('friendly_name', $keyword);
        $this->db->order_by("friendly_name", "asc");
        
        $query = $this->db->get();
        foreach($query->result_array() as $row){
            //$data[$row['friendly_name']];
            $data[] = $row;
        }
        //return $data;
        return $query;
    }
Processing your request, Please wait....

No Responses to “How to create a Codeigniter Auto Complete Search”

Comments (Your Comments)

Leave a Reply

You must be logged in to post a comment.