jQuery Autocomplete + PHP5 (Codeigniter) + MySQL – simple way

Requirements:

  1. jQuery – ползвам jQuery 1.8.2
  2. jQuery-UI – <script src=”http://code.jquery.com/ui/1.9.0/jquery-ui.js”></script>
  3. jQuery-UI css – <link rel=”stylesheet” href=”http://code.jquery.com/ui/1.9.0/themes/base/jquery-ui.css” />
JS code:
$(“name”).autocomplete({
        source: function(request, response) {
            $.ajax({ 
                url: “/url/url2”,
                data: { term: $(“name”).val()},
                dataType: “json”,
                type: “POST”,
                success: function(data){
                    
                    response($.map(data, function (item) {
                        return {
                            value: item
                        }
                    }))
                }
            });
        },
    minLength: 2
    });
Send data to “/url/url2” as POST in JSON format.
URL routing:
$route[‘/url/url2’] = “controller/action”;
saying that the post is going to the given controller and action.
In the controller:
  public function method()
        {
            if(isset($_POST[‘term’]))
            {
                $getTerm = $_POST[‘term’];
                $results = $this->my_model->get_data($getTerm);
                echo json_encode($results);
                flush();
            }
            
        }
In the Database layer(My_model):
public function get_data($getTerm)
        {
            $this->db->select(‘ DISTINCT EXTRACT(YEAR from Datings) as Years FROM Datings’, FALSE); 
            $this->db->like(‘Year’, $getTerm);
            $this->db->order_by(“Years”, ‘asc’);
            $query = $this->db->get();
            
            return $query->result();
        }

You may also like...