article

Sunday, August 4, 2013

CodeIgniter - jquery-ajax, jQueryUI - Autocomplete

CodeIgniter - jquery-ajax, jQueryUI - Autocomplete

Create Database table 

CREATE TABLE `country` (
  `id` smallint(5) UNSIGNED NOT NULL,
  `printable_name` varchar(255) NOT NULL,
  `CountryAbbrev` varchar(10) DEFAULT NULL,
  `CurrencyAbbr` varchar(4) DEFAULT NULL,
  `CurrencyRate` float DEFAULT NULL,
  `CurrencyCode` varchar(3) DEFAULT NULL
) ENGINE=MyISAM DEFAULT CHARSET=latin1;

ALTER TABLE `country`
  ADD PRIMARY KEY (`id`);

ALTER TABLE `country`
  MODIFY `id` smallint(5) UNSIGNED NOT NULL AUTO_INCREMENT, AUTO_INCREMENT=289;

Create Controller
application\controllers\autocomplete.php

<?php  if (!defined('BASEPATH')) exit('No direct script access allowed');

class Autocomplete extends CI_Controller { 
 
 public function __construct()  {
        parent:: __construct();
  $this->load->model("MAutocomplete");
  $this->load->helper("url");
  $this->load->helper('form');
    }
     
    public function index(){
        $this->load->view('autocomplete/show');
    }
     
    public function lookup(){
        // process posted form data
        $keyword = $this->input->post('term');
        $data['response'] = 'false'; //Set default response
        $query = $this->MAutocomplete->lookup($keyword); //Search DB
        if( ! empty($query) )
        {
            $data['response'] = 'true'; //Set response
            $data['message'] = array(); //Create array
            foreach( $query as $row )
            {
                $data['message'][] = array( 
                                        'id'=>$row->id,
                                        'value' => $row->printable_name,
                                        ''
                                     );  //Add a row to array
            }
        }
        if('IS_AJAX')
        {
            echo json_encode($data); //echo json string if ajax request
             
        }
        else
        {
            $this->load->view('autocomplete/index',$data); //Load html view of search results
        }
    }
}
Create Modal application\models\MAutocomplete.php
<?php
class MAutocomplete extends CI_Model{
    function lookup($keyword){
        $this->db->select('*')->from('country');
        $this->db->like('printable_name',$keyword,'after');
        $query = $this->db->get();    
         
        return $query->result();
    }
}
Create Viewapplication\views\autocomplete\show.php
<html lang="en-US">
    <head>
        <title>Codeigniter Autocomplete</title>
        <link rel="stylesheet" href="http://ajax.googleapis.com/ajax/libs/jqueryui/1.8.6/themes/base/jquery-ui.css" type="text/css" media="all" />
        <link rel="stylesheet" href="http://static.jquery.com/ui/css/demo-docs-theme/ui.theme.css" type="text/   css" media="all" />
        <script src="http://ajax.googleapis.com/ajax/libs/jquery/1.4.3/jquery.min.js" type="text/javascript"></script>
        <script src="http://ajax.googleapis.com/ajax/libs/jqueryui/1.8.6/jquery-ui.min.js" type="text/javascript"></script>
        <meta charset="UTF-8">
         
        <style>
            /* Autocomplete
            ----------------------------------*/
            .ui-autocomplete { position: absolute; cursor: default; }   
            .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; }*/
 
            /* workarounds */
            * html .ui-autocomplete { width:1px; } /* without this, the menu expands to 100% in IE6 */
 
            /* Menu
            ----------------------------------*/
            .ui-menu {
                list-style:none;
                padding: 2px;
                margin: 0;
                display:block;
            }
            .ui-menu .ui-menu {
                margin-top: -3px;
            }
            .ui-menu .ui-menu-item {
                margin:0;
                padding: 0;
                zoom: 1;
                float: left;
                clear: left;
                width: 100%;
                font-size:80%;
            }
            .ui-menu .ui-menu-item a {
                text-decoration:none;
                display:block;
                padding:.2em .4em;
                line-height:1.5;
                zoom:1;
            }
            .ui-menu .ui-menu-item a.ui-state-hover,
            .ui-menu .ui-menu-item a.ui-state-active {
                font-weight: normal;
                margin: -1px;
            }
        </style>
         
        <script type="text/javascript">
        $(this).ready( function() {
            $("#id").autocomplete({
                minLength: 1,
                source: 
                function(req, add){
                    $.ajax({
                        url: "<?php echo base_url(); ?>index.php/autocomplete/lookup",
                        dataType: 'json',
                        type: 'POST',
                        data: req,
                        success:    
                        function(data){
                            if(data.response =="true"){
                                add(data.message);
                            }
                        },
                    });
                },
            select: 
                function(event, ui) {
                    $("#result").append(
                        "<li>"+ ui.item.value + "</li>"
                    );                  
                },      
            });
        });
        </script>
         
    </head>
    <body>
        Country :
        <?php
            echo form_input('printable_name','','id="id"');
        ?>
        <ul>
            <div id="result"></div>
        </ul>
    </body>
</html>
View http://localhost/CODEIGNATER/autocomplete
/ Download http://bit.ly/2EaD1fA

Related Post