php - Codeigniter Autocomplete search box with JSON, MySql -
i'm trying make autocomplete search box code doesn't work, i'm trying 3 days. need autocomplete search result system. have tried several ways. in view, don't response or error. after typing 1 letter doesn't tell anything
code on controller
<?php if ( ! defined('basepath')) exit('no direct script access allowed'); class search extends ci_controller { function __construct() { parent::__construct(); } public function index() { $this->load->view('search'); } public function getfunction() { if ( !isset($_get['term']) ) exit; $term = $_request['term']; $data = array(); $rows = $this->model_search->getdata($term); foreach( $rows $row ) { $data[] = array( 'label' => $row->bname.', '. $row->bname, 'value' => $row->bname); } echo json_encode($data); flush(); } } and model code is
<?php if ( ! defined('basepath')) exit('no direct script access allowed'); class model_search extends ci_model { public function __construct() { parent::__construct(); // own constructor code } function getdata($term) { $sql = $this->db->query('select * brands bname "'. mysql_real_escape_string($term) .'%" order bname asc limit 0,10'); return $sql ->result(); } } view code is;
<html lang="en-us"> <head> <title>codeigniter autocomplete</title> <link rel="stylesheet" href="<?php echo base_url('assets/css/jquery-ui.css'); ?>" type="text/css" media="all" /> <script src="<?php echo base_url('assets/js/jquery-ui.js'); ?>" type="text/javascript"></script> <script src="<?php echo base_url('assets/js/jquery-1.8.3.js'); ?>" type="text/javascript"></script> <meta charset="utf-8"> <script type="text/javascript"> $(document).ready(function(){ $(function() { function split( val ) { return val.split( /,\s*/ ); } function extractlast( term ) { return split( term ).pop(); } $( "#txtinput" ) // don't navigate away field on tab when selecting item .bind( "keydown", function( event ) { if ( event.keycode === $.ui.keycode.tab && $( ).data( "autocomplete" ).menu.active ) { event.preventdefault(); } }) .autocomplete({ source: function( request, response ) { $.getjson( "<?php echo base_url();?>search/getfunction",{ term: extractlast( request.term ) },response ); }, search: function() { // custom minlength var term = extractlast( this.value ); if ( term.length < 1 ) { return false; } }, focus: function() { // prevent value inserted on focus return false; }, select: function( event, ui ) { var terms = split( this.value ); // remove current input terms.pop(); // add selected item terms.push( ui.item.value ); // add placeholder comma-and-space @ end terms.push( "" ); this.value = terms.join( "," ); return false; } }); }); }); </script> </head> <body> <input type="text" id="txtinput" size="20" /> </body> </html>
Comments
Post a Comment