How to use jquery Autocomplete with Codeigniter

How to use jquery Autocomplete with Codeigniter

In this post, I will show how to use jquery autocomplete with codeigniter framework.Many times we need autocomplete suggestion for web application to show list of data available in database. Jquery autocomplete provides suggestion list when user start typing into input field.

Follow me step by step We gonna use jquery autocomplete library.

1.) first we create a view where we using a input field to implement jquery autocomplete functionality.Here is the code below.


<title>Autocomplete Example</title>
<link rel="stylesheet" href="">
font-family: Verdana;
font-size: 18pt;
font-style: normal;
font-weight: bold;
text-align: center;
font-family: Verdana;
font-size: 12pt;
font-style: normal;
font-weight: bold;
border-collapse: collapse;
  font-size: 11px;
<h3>Atocomplete Example</h3>
<?php echo form_open('autocomplete',array('name'=>'autocomplete')); ?>
    <table align="center" cellpadding = "5">
            <td><input type="text" size="40px" name="name" id="name" /></td>
            <td class="error"><?php echo form_error('name'); ?></td>
    <input type="hidden" size="40px" name="userId" id="userId" />
<?php echo form_close();?>
<script src="" type="text/javascript"></script>
<script src="" type="text/javascript"></script>
<script src=""></script>
<script src=""></script>
<script language="javascript" type="text/javascript">
$J = jQuery.noConflict();
$J( function() {
source: function(request, response) {
url: "<?php echo base_url();?>user/getAllUsers",
data: { code: $("#name").val()},
dataType: "JSON",
type: "POST",
success: function(data){
                var array = data.error ? [] : $.map(data.list,function(m){
     focus: function(event, ui) {
    select: function (event, ui) {
minLength: 1

2.) Next we create a controller where we are get all data from database and encode with json to pass into view and populate in autocomplete suggestion box.Please find below the code. 

UserController .php

defined('BASEPATH') OR exit('No direct script access allowed');
class UserController extends CI_Controller {
publicfunction __construct()
    public function index() {
public function getAllUsers(){
         $name = $this->input->post('name',TRUE);
         $dataUsers = $this->db->select('name,id')->from('tbl_user')->like('name',$name)->limit(10,0)->get()->result();
         $data = array(
         'list' => $dataUsers
         echo json_encode($data);

4.) Change the routes as showing below.

$route['user'] = 'UserController/index';
$route['user/getAllUsers'] = 'UserController/getAllUsers';

Now,move on to browser and type in URL http:\\localhost\myapp\user.When you start typing into input box you will get interface as showing in below.