Codeigniter Auto Complete Search


/ Published in: PHP
Save to your folder(s)

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.


Copy this code and paste it in your HTML
  1. // js code after document is ready
  2. // Search autocomplete
  3. $("#swSearch").autocomplete({
  4. minLength: 1,
  5. source: function(req, add){
  6. $.ajax({
  7. url: '/search', //Controller where search is performed
  8. dataType: 'json',
  9. type: 'POST',
  10. data: req,
  11. success: function(data){
  12. if(data.response =='true'){
  13. add(data.message);
  14. }
  15. }
  16. });
  17. }
  18. });
  19.  
  20.  
  21.  
  22.  
  23.  
  24. // Controller search function
  25.  
  26. $keyword = $this->input->post('term');
  27.  
  28. $data['response'] = 'false'; //Set default response
  29.  
  30. $query = $this->Mprofile->sw_search($keyword); //Model DB search
  31.  
  32. if($query->num_rows() > 0){
  33. $data['response'] = 'true'; //Set response
  34. $data['message'] = array(); //Create array
  35. foreach($query->result() as $row){
  36. $data['message'][] = array('label'=> $row->friendly_name, 'value'=> $row->friendly_name); //Add a row to array
  37. }
  38. }
  39. echo json_encode($data);
  40.  
  41.  
  42.  
  43. // Simple model example
  44.  
  45. public function sw_search($keyword)
  46. {
  47. $this->db->select('id, friendly_name');
  48. $this->db->from('business_category');
  49. $this->db->where('suppress', 0);
  50. $this->db->like('friendly_name', $keyword);
  51. $this->db->order_by("friendly_name", "asc");
  52.  
  53. $query = $this->db->get();
  54. foreach($query->result_array() as $row){
  55. //$data[$row['friendly_name']];
  56. $data[] = $row;
  57. }
  58. //return $data;
  59. return $query;
  60. }

Report this snippet


Comments

RSS Icon Subscribe to comments

You need to login to post a comment.