Codeigniter Autocomplete with
Jquery UI [Complete Guide]
FEBRUARY 20, 2018
If you are serious about codeigniter, you should learn how to create
autocomplete with codeigniter.
Why?
Because, User Experience (UX) is the most important thing in an
application. If you ignore the User Experience, you are in trouble.
In this tutorial, you will learn all the things you need to know about
how to create autocomplete with codeigniter.
Let’s get start it.
What is Autocomplete?
Autocomplete is a suggestion that is displayed to increase user
experience (UX).
If you googling on google and typing some keywords, then you will
see autocomplete like this:
If you search for your favorite videos on youtube, you will also find
autocomplete like this:
So, how to create autocomplete like google and youtube?
Let’s get start it.
Step 1. Preparation
This is important!
If you missed this step, it means you missed the whole of this tutorial.
Good preparation will determine your success following this tutorial.
The better your preparation, the more likely you will succeed in
following this tutorial.
Do not skip this step, though it feels complex.
So, what do you need to prepare?
Here’s the list:
1. Codeiginter
Codeigniter is the main php framework we will use in this tutorial. If
you do not have it yet, please download it at the official
website: www.codeigniter.com
2. Bootstrap
Bootstrap is a framework to beautify the user interface (UI). If you do
not have it yet, please download it first at the official
website: www.getbootstrap.com
3. Jquery
This is important!
Jquery is a javascript library that serves to help simplify the
manipulation of html elements and run the autocomplete well.
If you do not have it yet, please download it at the official
website: www.jquery.com
4. Jquery UI
Jquery UI is a javascript library that helps make autocomplete easier.
If you do not have it yet, please download it at the official
website: http://jqueryui.com/
Step 2. Database preparation
In this tutorial, I use mysql as Database Management System
(DBMS).
If you also use mysql, you will love this tutorial.
But,
If you are using other DBMS like Oracle, SQL Server, Maria DB, or
MongoDB.
No, Problem!
Provided you understand SQL (Structured Query Language) better.
Ok, Let's continue!
Please create a database, here I create a database with
named autocomplete_db.
If you create a database with the same name it will be better.
Please execute this query to create the database:
1 CREATE DATABASE autocomplete_db;
That query will generate a database with named autocomplete_db.
Next,
Create a table with name blog with structure like this:
To create a table structure like the picture above,
You could follow this query:
1 CREATE TABLE blog(
2 blog_id INT(11) PRIMARY KEY AUTO_INCREMENT,
3 blog_title VARCHAR(100),
4 blog_description TEXT
)ENGINE=INNODB;
5
Next, insert some data in the blog table by executing the following
query:
1 INSERT INTO blog (blog_title,blog_description) VALUES
('Basic Database System','Complete Guide Basic of database system for beginner'),
2
('Upload Image using codeigniter','Easy way to create upload image using codeigniter
3
('CRUD with codeigniter and Bootstrap','This is tutorial how to create CRUD applicat
4 bootstrap');
So that look like this:
Step 3. Codeigniter Installation
Next,
Extract codeigniter that has been downloaded earlier to www folder
(if you use wampserver) or htdocs (if you use XAMPP).
Because I use wampserver. So, I extract it to c:/wamp/www/
And then, rename codeigniter project to be autocomplete.
Like this:
Open autocomplete folder and create assets folder, And then
create css and js folder inside the assets folder. After that, include
the bootstrap, jquery UI, and jquery files inside
the css and js folder.
So that look like this:
Step 4. Codeigniter Configuration
Next step is the configuration on the codeigniter.
Here are some files you need to configure:
1. Autoload.php
To configure the autoload.php, please open the folder:
application/config/autoload.php
like this:
Open autoload.php using text editor like Notepad++ or Sublime Text.
And then find this code:
1 $autoload['libraries'] = array();
2 $autoload['helper'] = array();
Set to be like this:
1 $autoload['libraries'] = array('database');
2 $autoload['helper'] = array('url');
2. Config.php
To configure the config.php, please open the folder:
application/config/config.php
like this:
Open config.php file using text editor, and then find this code:
1 $config['base_url'] = '';
And then set to be like this:
1 $config['base_url'] = 'http://localhost/autocomplete/';
3. Database.php
To configure the database.php, please open the folder:
application/config/database.php
like this:
Open database.php file using text editor, and then find this code:
1 $active_group = 'default';
$query_builder = TRUE;
2
3
$db['default'] = array(
4
'dsn' => '',
5
'hostname' => 'localhost',
6
'username' => '',
7
'password' => '',
8 'database' => '',
9 'dbdriver' => 'mysqli',
10 'dbprefix' => '',
11 'pconnect' => FALSE,
'db_debug' => (ENVIRONMENT !== 'production'),
12
'cache_on' => FALSE,
13
'cachedir' => '',
14
'char_set' => 'utf8',
15
'dbcollat' => 'utf8_general_ci',
16 'swap_pre' => '',
17 'encrypt' => FALSE,
18 'compress' => FALSE,
19 'stricton' => FALSE,
20 'failover' => array(),
'save_queries' => TRUE
21
);
22
23
24
And then Set to be like this:
$active_group = 'default';
1
$query_builder = TRUE;
2
3
$db['default'] = array(
4
'dsn' => '',
5
'hostname' => 'localhost',
6 'username' => 'root',
7 'password' => '',
8 'database' => 'autocomlete_db',
9 'dbdriver' => 'mysqli',
'dbprefix' => '',
10
'pconnect' => FALSE,
11
'db_debug' => (ENVIRONMENT !== 'production'),
12
'cache_on' => FALSE,
13
'cachedir' => '',
14 'char_set' => 'utf8',
15 'dbcollat' => 'utf8_general_ci',
'swap_pre' => '',
16
'encrypt' => FALSE,
17
'compress' => FALSE,
18
'stricton' => FALSE,
19
'failover' => array(),
20 'save_queries' => TRUE
21 );
22
23
24
Step 5. Controller
Go ahead and create a controller file controllers/Blog.php with the
following this code:
1 <?php
2 class Blog extends CI_Controller{
function __construct(){
3
parent::__construct();
4
$this->load->model('blog_model');
5
}
6
7
function index(){
8
$this->load->view('blog_view');
9 }
10
11 function get_autocomplete(){
12 if (isset($_GET['term'])) {
13 $result = $this->blog_model->search_blog($_GET['term']);
14 if (count($result) > 0) {
foreach ($result as $row)
15
$arr_result[] = $row->blog_title;
16
echo json_encode($arr_result);
17
}
18
}
19 }
20
21 }
22
23
Step 6. Model
Go ahead and create a model file models/Blog_model.php with the
following this code:
1
<?php
2
class Blog_model extends CI_Model{
3
4 function search_blog($title){
5 $this->db->like('blog_title', $title , 'both');
6 $this->db->order_by('blog_title', 'ASC');
7 $this->db->limit(10);
return $this->db->get('blog')->result();
8
}
9
10
}
11
Step 7. View
Go ahead and create a view file views/blog_view.php with the
following this code:
1 <!DOCTYPE html>
<html>
2
<head>
3
<meta charset="utf-8">
4
<meta name="viewport" content="width=device-width, initial-scale=1, shrink-to-fi
5
<title>Autocomplete</title>
6 <link rel="stylesheet" href="<?php echo base_url().'assets/css/bootstrap.css'?>"
7 <link rel="stylesheet" href="<?php echo base_url().'assets/css/jquery-ui.css'?>"
8 </head>
9 <body>
<div class="container">
10
<div class="row">
11
<h2>Autocomplete Codeigniter</h2>
12
</div>
13
<div class="row">
14
<form>
15 <div class="form-group">
16 <label>Title</label>
17 <input type="text" class="form-control" id="title" placeholder="T
18 </div>
</form>
19
</div>
20
</div>
21
22
<script src="<?php echo base_url().'assets/js/jquery-3.3.1.js'?>" type="text/ja
23
<script src="<?php echo base_url().'assets/js/bootstrap.js'?>" type="text/javas
24
<script src="<?php echo base_url().'assets/js/jquery-ui.js'?>" type="text/javas
25 <script type="text/javascript">
26 $(document).ready(function(){
27 $( "#title" ).autocomplete({
source: "<?php echo site_url('blog/get_autocomplete/?');?>"
28
});
29
});
30
</script>
31
32
</body>
33 </html>
34
35
36
37
Done.
Open your browser, and visit the following url:
http://localhost/autocomplete/index.php/blog/
Then it will appear form with input text. And then type a few keywords
from the blog title in the database, then you will see autocomplete
like this:
But Wait.!!!
I will not leave you soon, let's explore the customize.
This is important!!!
Autocomple Dropdown
Autocomplete dropdown is autocomplete where when one option of
autocomplete is selected, it will show other related fields.
Example:
When one option of autocomplete is selected, it will show the other
related fields. Like this:
How to create autocomplete like that?
Let’s begin.
Open the controller Blog.php, and then change
the get_autocomplete method to be like this:
1 function get_autocomplete(){
2 if (isset($_GET['term'])) {
$result = $this->blog_model->search_blog($_GET['term']);
3
if (count($result) > 0) {
4
foreach ($result as $row)
5
$arr_result[] = array(
6
'label' => $row->blog_title,
7
'description' => $row->blog_description,
8
);
9
echo json_encode($arr_result);
10 }
11 }
12 }
13
After that, open view blog_view.php, and then change to be like this:
1 <!DOCTYPE html>
2 <html>
<head>
3
<meta charset="utf-8">
4
<meta name="viewport" content="width=device-width, initial-scale=1, shrink-to-fi
5
<title>Autocomplete</title>
6
<link rel="stylesheet" href="<?php echo base_url().'assets/css/bootstrap.css'?>"
7 <link rel="stylesheet" href="<?php echo base_url().'assets/css/jquery-ui.css'?>"
8 </head>
9 <body>
10 <div class="container">
<div class="row">
11
<h2>Autocomplete Codeigniter</h2>
12
</div>
13
<div class="row">
14
<form>
15
<div class="form-group">
16 <label>Title</label>
17 <input type="text" name="title" class="form-control" id="title" pl
18 </div>
19 <div class="form-group">
<label>Description</label>
20
<textarea name="description" class="form-control" placeholder="D
21
</div>
22
</form>
23
</div>
24
</div>
25
26 <script src="<?php echo base_url().'assets/js/jquery-3.3.1.js'?>" type="text/ja
27 <script src="<?php echo base_url().'assets/js/bootstrap.js'?>" type="text/javas
28 <script src="<?php echo base_url().'assets/js/jquery-ui.js'?>" type="text/javas
29 <script type="text/javascript">
$(document).ready(function(){
30
31
$('#title').autocomplete({
32
source: "<?php echo site_url('blog/get_autocomplete');?>",
33
34
select: function (event, ui) {
35
$('[name="title"]').val(ui.item.label);
36 $('[name="description"]').val(ui.item.description);
37 }
38 });
39
40 });
41 </script>
42
</body>
43
</html>
44
45
46
47
48
In the blog_view.php file, there is addition of one
component textarea and there is a change in javascript.
Done,
Congratulation you are succeed to create autocomplete dropdown.
Please visit URL http://localhost/autocomplete/index.php/blog/ for
testing.
Autocomplete Auto Submit Form
If you go to google and type something and autocomplete appears,
when you select an option from autocomplete, then the search form
directly submitted without clicking search button.
How to create autocomplete like that?
Let’s begin.
Create a new controller named Tutorial.php with the following code:
1 <?php
2 class Tutorial extends CI_Controller{
function __construct(){
3
parent::__construct();
4
$this->load->model('blog_model');
5
error_reporting(0);
6
}
7
8 function index(){
9 $this->load->view('tutorial_view');
10 }
11
12 function get_autocomplete(){
13 if (isset($_GET['term'])) {
$result = $this->blog_model->search_blog($_GET['term']);
14
if (count($result) > 0) {
15
foreach ($result as $row)
16
$arr_result[] = array(
17
'label' => $row->blog_title,
18 );
19 echo json_encode($arr_result);
20 }
21 }
22 }
23
function search(){
24
$title=$this->input->get('title');
25
$data['data']=$this->blog_model->search_blog($title);
26
27
$this->load->view('search_view',$data);
28
}
29
30 }
31
32
33
After that create more view files. Here we need two more views.
View for search form (tutorial_view.php) and view to display search
result (search_view.php).
First, create a view tutorial_view.php with the following code:
1 <!DOCTYPE html>
2 <html>
3 <head>
<meta charset="utf-8">
4
<meta name="viewport" content="width=device-width, initial-scale=1, shrink-to-fi
5
<title>Autocomplete</title>
6
<link rel="stylesheet" href="<?php echo base_url().'assets/css/bootstrap.css'?>"
7
<link rel="stylesheet" href="<?php echo base_url().'assets/css/jquery-ui.css'?>"
8 </head>
9 <body>
10 <div class="container">
11 <div class="row">
12 <h2>Search</h2>
</div>
13
<div class="row">
14
<form id="form_search" action="<?php echo site_url('tutorial/search');?>
15
<div class="input-group">
16
<input type="text" name="title" class="form-control" id="title" pl
17 <span class="input-group-btn">
18 <button class="btn btn-info" type="submit">Search</button>
19 </span>
20 </div>
21 </form>
</div>
22
</div>
23
24
<script src="<?php echo base_url().'assets/js/jquery-3.3.1.js'?>" type="text/ja
25
<script src="<?php echo base_url().'assets/js/bootstrap.js'?>" type="text/javas
26
<script src="<?php echo base_url().'assets/js/jquery-ui.js'?>" type="text/javas
27 <script type="text/javascript">
28 $(document).ready(function(){
29
30 $('#title').autocomplete({
31 source: "<?php echo site_url('tutorial/get_autocomplete');?>",
32
33 select: function (event, ui) {
34 $(this).val(ui.item.label);
$("#form_search").submit();
35
}
36
});
37
38
});
39
</script>
40
41 </body>
42 </html>
43
44
45
46
After that, create the view again and give
name search_view.php with code as follows:
1 <!DOCTYPE html>
2 <html>
3 <head>
4 <meta charset="utf-8">
<meta name="viewport" content="width=device-width, initial-scale=1, shrink-to-fi
5
<title>Search Result</title>
6
<link rel="stylesheet" href="<?php echo base_url().'assets/css/bootstrap.css'?>"
7
</head>
8
<body>
9 <div class="container">
10 <div class="row">
11 <h2>Search Result</h2>
12 </div>
13 <div class="row">
14 <table class="table table-striped">
15 <thead>
<tr>
16
<th>Title</th>
17
<th>Description</th>
18
</tr>
19
</thead>
20 <tbody>
21 <?php foreach($data as $row):?>
22 <tr>
23 <td><?php echo $row->blog_title;?></td>
24 <td><?php echo $row->blog_description;?></td>
</tr>
25
<?php endforeach;?>
26
</tbody>
27
</table>
28
</div>
29 </div>
30
31 <script src="<?php echo base_url().'assets/js/jquery-3.3.1.js'?>" type="text/ja
32 <script src="<?php echo base_url().'assets/js/bootstrap.js'?>" type="text/javas
33
34 </body>
35 </html>
36
37
38
Done.
Now, please visit the
URL http://localhost/autocomplete/index.php/tutorial for testing.
If it goes well, it will look like this:
Type in the keyword "codeigniter" then it will look like this:
And then click one of the options autocomplete available, then the
form will be directly submitted without the need to click the search
button
Awesome right?
And then, you will see the result look like this:
Congratulations, you did it.!
Conclusion
In today's tutorial is how to create autocomplete with codeigniter and
jquery UI.
Autocomplete is a suggestion shown to improve User
Experience (UX).
There are 3 types of autocompletes that you have learned: how to
display autocomplete from the database, how to create autocomplete
dropdown, and how to create a search with autocomplete auto
submit form.