/ Published in: PHP
example I used to create a auto suggest search from that pulls from a database. The example pulls from a single db table containing categories. Using jQueryUI made this pretty painless but by default the autocomplete feature uses GET variables and you must enable these in your Codeigniter settings to work properly.\r\n\r\nThis example uses POST variables instead so the js is modified accordingly.
Expand |
Embed | Plain Text
Copy this code and paste it in your HTML
// 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 foreach($query->result() as $row){ $data['message'][] = array('label'=> $row->friendly_name, 'value'=> $row->friendly_name); //Add a row to array } } // 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; }