Thursday, August 15, 2013

CodeIgniter - jquery-ajax, jQueryUI - Autocomplete

CodeIgniter - jquery-ajax, jQueryUI - Autocomplete

Create Database table 

CREATE TABLE IF NOT EXISTS `country` (
  `id` int(11) NOT NULL AUTO_INCREMENT,
  `iso` char(2) NOT NULL DEFAULT '',
  `printable_name` varchar(80) NOT NULL DEFAULT '',
  `iso3` char(3) DEFAULT NULL,
  `numcode` smallint(6) DEFAULT NULL,
  PRIMARY KEY (`iso`),
  KEY `id` (`id`),
  KEY `id_2` (`id`)
) ENGINE=MyISAM  DEFAULT CHARSET=latin1 AUTO_INCREMENT=240 ;

Insert Data
INSERT INTO `country` (`id`, `iso`, `printable_name`, `iso3`, `numcode`) VALUES
(165, 'PA', 'Panama', 'PAN', 591),
(166, 'PG', 'Papua New Guinea', 'PNG', 598),
(167, 'PY', 'Paraguay', 'PRY', 600),
(168, 'PE', 'Peru', 'PER', 604),
(169, 'PH', 'Philippines', 'PHL', 608);

Create Controller
application\controllers\autocomplete.php


  1. <?php  if (!defined('BASEPATH')) exit('No direct script access allowed');  
  2.   
  3. class Autocomplete extends CI_Controller {   
  4.    
  5.  public function __construct()  {  
  6.         parent:: __construct();  
  7.   $this->load->model("MAutocomplete");  
  8.   $this->load->helper("url");  
  9.   $this->load->helper('form');  
  10.     }  
  11.        
  12.     public function index(){  
  13.         $this->load->view('autocomplete/show');  
  14.     }  
  15.        
  16.     public function lookup(){  
  17.         // process posted form data  
  18.         $keyword = $this->input->post('term');  
  19.         $data['response'] = 'false'//Set default response  
  20.         $query = $this->MAutocomplete->lookup($keyword); //Search DB  
  21.         if( ! empty($query) )  
  22.         {  
  23.             $data['response'] = 'true'//Set response  
  24.             $data['message'] = array(); //Create array  
  25.             foreach( $query as $row )  
  26.             {  
  27.                 $data['message'][] = array(   
  28.                                         'id'=>$row->id,  
  29.                                         'value' => $row->printable_name,  
  30.                                         ''  
  31.                                      );  //Add a row to array  
  32.             }  
  33.         }  
  34.         if('IS_AJAX')  
  35.         {  
  36.             echo json_encode($data); //echo json string if ajax request  
  37.                
  38.         }  
  39.         else  
  40.         {  
  41.             $this->load->view('autocomplete/index',$data); //Load html view of search results  
  42.         }  
  43.     }  
  44. }  
Create Modal application\models\MAutocomplete.php
  1. <?php  
  2. class MAutocomplete extends CI_Model{  
  3.     function lookup($keyword){  
  4.         $this->db->select('*')->from('country');  
  5.         $this->db->like('printable_name',$keyword,'after');  
  6.         $query = $this->db->get();      
  7.            
  8.         return $query->result();  
  9.     }  
  10. }  
Create Viewapplication\views\autocomplete\show.php
  1. <html lang="en-US">  
  2.     <head>  
  3.         <title>Codeigniter Autocomplete</title>  
  4.         <link rel="stylesheet" href="http://ajax.googleapis.com/ajax/libs/jqueryui/1.8.6/themes/base/jquery-ui.css" type="text/css" media="all" />  
  5.         <link rel="stylesheet" href="http://static.jquery.com/ui/css/demo-docs-theme/ui.theme.css" type="text/   css" media="all" />  
  6.         <script src="http://ajax.googleapis.com/ajax/libs/jquery/1.4.3/jquery.min.js" type="text/javascript"></script>  
  7.         <script src="http://ajax.googleapis.com/ajax/libs/jqueryui/1.8.6/jquery-ui.min.js" type="text/javascript"></script>  
  8.         <meta charset="UTF-8">  
  9.            
  10.         <style>  
  11.             /* Autocomplete 
  12.             ----------------------------------*/  
  13.             .ui-autocomplete { position: absolute; cursor: default; }     
  14.             .ui-autocomplete-loading { background: white url('http://jquery-ui.googlecode.com/svn/tags/1.8.2/themes/flick/images/ui-anim_basic_16x16.gif') right center no-repeat; }*/  
  15.    
  16.             /* workarounds */  
  17.             * html .ui-autocomplete { width:1px; } /* without this, the menu expands to 100% in IE6 */  
  18.    
  19.             /* Menu 
  20.             ----------------------------------*/  
  21.             .ui-menu {  
  22.                 list-style:none;  
  23.                 padding: 2px;  
  24.                 margin: 0;  
  25.                 display:block;  
  26.             }  
  27.             .ui-menu .ui-menu {  
  28.                 margin-top: -3px;  
  29.             }  
  30.             .ui-menu .ui-menu-item {  
  31.                 margin:0;  
  32.                 padding: 0;  
  33.                 zoom: 1;  
  34.                 float: left;  
  35.                 clear: left;  
  36.                 width: 100%;  
  37.                 font-size:80%;  
  38.             }  
  39.             .ui-menu .ui-menu-item a {  
  40.                 text-decoration:none;  
  41.                 display:block;  
  42.                 padding:.2em .4em;  
  43.                 line-height:1.5;  
  44.                 zoom:1;  
  45.             }  
  46.             .ui-menu .ui-menu-item a.ui-state-hover,  
  47.             .ui-menu .ui-menu-item a.ui-state-active {  
  48.                 font-weight: normal;  
  49.                 margin: -1px;  
  50.             }  
  51.         </style>  
  52.            
  53.         <script type="text/javascript">  
  54.         $(this).ready( function() {  
  55.             $("#id").autocomplete({  
  56.                 minLength: 1,  
  57.                 source:   
  58.                 function(req, add){  
  59.                     $.ajax({  
  60.                         url: "<?php echo base_url(); ?>index.php/autocomplete/lookup",  
  61.                         dataType: 'json',  
  62.                         type: 'POST',  
  63.                         data: req,  
  64.                         success:      
  65.                         function(data){  
  66.                             if(data.response =="true"){  
  67.                                 add(data.message);  
  68.                             }  
  69.                         },  
  70.                     });  
  71.                 },  
  72.             select:   
  73.                 function(event, ui) {  
  74.                     $("#result").append(  
  75.                         "<li>"+ ui.item.value + "</li>"  
  76.                     );                    
  77.                 },        
  78.             });  
  79.         });  
  80.         </script>  
  81.            
  82.     </head>  
  83.     <body>  
  84.         Country :  
  85.         <?php  
  86.             echo form_input('printable_name','','id="id"');  
  87.         ?>  
  88.         <ul>  
  89.             <div id="result"></div>  
  90.         </ul>  
  91.     </body>  
  92. </html>  
View http://localhost/CODEIGNATER/autocomplete