autocomplete in codeigniter

2019-05-12 17:27发布

问题:

I tried to do autocomplete in codeignter using the code that I got from a site.But it is not working for me.Can anyone find the problem

The view function that I used is given below

<html>

    <head>
        <title>Autocomplete</title>

        <script src="<?php echo base_url().'js/jquery.autocomplete.js'?>"></script>
        <script src="<?php echo base_url().'js/jquery-1.6.4.js'?>"></script>

        <script type="text/javascript">

          $(function() {
          $( "#username" ).autocomplete({ //the recipient text field with id #username
          source: function( request, response ) {
            $.ajax({
                url: "http://localhost/autocomplete/index.php/autocontroller/search_username",
                dataType: "json",
                data: request,
                success: function(data){
                    if(data.response == 'true') {
                       response(data.message);
                    }
                }
            });
        }
    });
});

        </script>
    </head>

    <body>

        <h1>Autocomplete</h1>

        <input type="text" id="username" value="" />
    </body>

</html>

And the controller i have used is given below

<?php
/* 
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */

/**
 * Description of autocontroller
 *
 * @author Sivam
 */
class autocontroller extends CI_Controller {

    public function  __construct() {
        parent::__construct();
         $this->load->helper(array('form', 'url'));
         $this->load->database();
    }

    function index()
    {
        $this->load->view('autoview');
    }

    function search_username()
{
        $username = trim($this->input->get('term', TRUE)); //get term parameter sent via text field. Not sure how secure get() is

        $this->db->select('fname');
        $this->db->from('users');
        $this->db->like('fname', $username);
        $this->db->limit('5');
        $query = $this->db->get();

        if ($query->num_rows() > 0)
        {
            $data['response'] = 'true'; //If username exists set true
            $data['message'] = array();

            foreach ($query->result() as $row)
            {
                $data['message'][] = array(
                    'label' => $row->fname,
                    'value' => $row->fname
                );
            }
        }
        else
        {
            $data['response'] = 'false'; //Set false if user not valid
        }

        echo json_encode($data);
}

}
?>

回答1:

I am not able to understand why you use

$data['message'][] = array(
                    'label' => $row->fname,
                    'value' => $row->fname
                );

You can try by single dimensional array.

$data['message'] = array(
                        'label' => $row->fname,
                        'value' => $row->fname
                    );

I have also use autocomplete by follwing this .http://www.jamipietila.fi/codeigniter-and-autocomplete-with-jquery/ Please try this...Its works for me ..Hopefully it will work for you as well.



回答2:

This is a simple way to use autocomplete in codeigniter. It worked for me.

In View:

<script src="http://code.jquery.com/jquery-1.10.2.min.js"></script>

<script type="text/javascript">
function lookup(inputString) {
if(inputString.length == 0) {
    $('#suggestions').hide();
} else {
    $.post("<?php echo base_url() ?>your_controller/your_action/"+inputString, function(data){
        if(data.length > 0) {
            $('#suggestions').show();
            $('#autoSuggestionsList').html(data);
        }
    });
}

}

function fill(thisValue) {
$('#id_input').val(thisValue);
  setTimeout("$('#suggestions').hide();", 200);
}
</script>


<?php echo form_input('company_name', '', "id='id_input' autocomplete='off' onKeyUp='lookup(this.value)'") ?>

<div id="suggestions">
  <div class="autoSuggestionsList_l" id="autoSuggestionsList"></div>
</div>

Here the first line is, ofcourse, to call the jquery library.

Next we have 2 functions. lookup() accepts the user input and then calls the relevant URL which will do the necessary database call.

The next function fill() will unload the div that will contain the resulting output.

Finally in the view, I added the text input box and also hooked the lookup function once user gives an input in box. Below the input box we have a div, which will show the result, if there is any. This div will be visible only when the user's input yields a result.

In Controller we have:

function autocomplete($a)
{
  $i = 0;
  $this->load->model('company');
  $companyList = $this->company->get_companies($a);

  if(count($companyList) > 0):
    echo "<ul>";
    foreach($companyList as $comp):
      echo "<li id='".$companyList[$i]['id']."'><a href='#'>".$companyList[$i]['name']."</a></li>";
      $i++;
    endforeach;
    echo "</ul>";
  endif;
} 

Here in the above function, it accepts the company name (or a part of it) and then I am calling a function get_companies() with the string. This function which will make the database call and return the result as a array.

In Model:

public function get_companies($name)
{
    //$this->db->_compile_select(); 
    $this->db->like('company_name', $name, 'after'); 

    //$this->db->where('id', $name);

    $query = $this->db->get('companies');

    //echo $this->db->last_query(); 
    //echo $query->num_rows();
    $companies = array();
    $i = 0;
    if($query->num_rows() > 0)
    {
        foreach ($query->result() as $row)
        {
            $companies[$i]['id'] = $row->id;
            $companies[$i]['name'] = $row->company_name;
            $i++;
        }


    }

    //print_r($companies);
    return $companies;


}

This above function is making the database call and returning the 2D array, one element being the id and another the name.