user3313127
user3313127

Reputation: 93

Codeigniter ajax autocomplite not working

Hello my ajaz autocomplite not work. Please tell me. Where is mistake? When I enter the letters - shows empty autocomplite without words. And i enter wrong words - autocomplite is not hide

model

class Auto_nickname extends CI_Model {
    function lookup($keyword) {
        $this->db->select('name')->from('unit');
        $this->db->like('nickname',$keyword,'after');
        $query = $this->db->get();
        return $query;
    }
}

controller

function q_nickname() {
    $this->load->database();
    $this->load->model("Auto_nickname");
    $keyword = $this->input->post('select_people');
    $query = $this->Auto_nickname->lookup($keyword);

    if ($query->num_rows() > 0) {
        $data = array(); //Create array
        foreach ($query->result() as $row) {
            $data[] = array(
                'name' => $row->name,
            );
        }
        echo json_encode($data);
    }

}

HTML + JS

<script>
$(document).ready(function () {
    $("#txt").autocomplete({
        source:baseUrl+"home/q_nickname",
        dataType: 'json',
        type: 'POST',
        minLength:1
    });
});
</script>
<input type="text" name="select_people" id="txt" />

Upvotes: 1

Views: 74

Answers (1)

Reena Shirale
Reena Shirale

Reputation: 2042

Model -

class Auto_nickname extends CI_Model
{
    function lookup($keyword)
    {
        $this->db->select('name')->from('unit');
        $this->db->like('nickname',$keyword,'after');
        $query = $this->db->get();
        return $query;
    }
} 

Controller

function q_nickname()
{
   $this->load->database();
   $this->load->model("Auto_nickname");
   $keyword = $this->input->post('select_people');
   $data['query'] = $this->Auto_nickname->lookup($keyword);
   $this->load->view('yourview',$data);
}

view-

<script>
  $(function() { 
       var names = [
            <?php
            //var_dump($query );
             foreach($query as $nm):
             if(isset($nm->nickname))
                 echo '"'.$nm->nickname.'",';
             endforeach; 
             ?>
                    "" , ];
            $( "#txt" ).autocomplete({
                source: names
            });
    });

<input type="text" name="select_people" id="txt" />

Upvotes: 1

Related Questions