Codeigniter Autocomplete with Jquery UI [Complete Guide]

Codeigniter Autocomplete with Jquery UI [Complete Guide]

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:

Google Autocomplete

If you search for your favorite videos on youtube, you will also find autocomplete like this:

Youtube Autocomplete

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:

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:

Database Structures

To create a table structure like the picture above,

You could follow this query:

CREATE TABLE blog(
blog_id INT(11) PRIMARY KEY AUTO_INCREMENT,
blog_title VARCHAR(100),
blog_description TEXT
)ENGINE=INNODB;  

Next, insert some data in the blog table by executing the following query:

INSERT INTO blog (blog_title,blog_description) VALUES 
('Basic Database System','Complete Guide Basic of database system for beginner'),
('Upload Image using codeigniter','Easy way to create upload image using codeigniter for beginner'),
('CRUD with codeigniter and Bootstrap','This is tutorial how to create CRUD application using codeigniter and bootstrap'); 

So that look like this:

Blog data

 

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:

Web Root

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:

Project Structure

 

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:

Autoload Config

Open autoload.php using text editor like Notepad++ or Sublime Text.

And then find this code:

$autoload['libraries'] = array();
$autoload['helper'] = array();

Set to be like this:

$autoload['libraries'] = array('database');
$autoload['helper'] = array('url');

 

2. Config.php

To configure the config.php, please open the folder:

application/config/config.php

like this:

Config Configure

Open config.php file using text editor, and then find this code:

$config['base_url'] = '';

And then set to be like this:

$config['base_url'] = 'http://localhost/autocomplete/';

 

3. Database.php

To configure the database.php, please open the folder:

application/config/database.php

like this:

Database Config

Open database.php file using text editor, and then find this code:

$active_group = 'default';
$query_builder = TRUE;

$db['default'] = array(
	'dsn'	=> '',
	'hostname' => 'localhost',
	'username' => '',
	'password' => '',
	'database' => '', 
	'dbdriver' => 'mysqli',
	'dbprefix' => '',
	'pconnect' => FALSE,
	'db_debug' => (ENVIRONMENT !== 'production'),
	'cache_on' => FALSE,
	'cachedir' => '',
	'char_set' => 'utf8',
	'dbcollat' => 'utf8_general_ci',
	'swap_pre' => '',
	'encrypt' => FALSE,
	'compress' => FALSE,
	'stricton' => FALSE,
	'failover' => array(),
	'save_queries' => TRUE
);

And then Set to be like this:

$active_group = 'default';
$query_builder = TRUE;

$db['default'] = array(
	'dsn'	=> '',
	'hostname' => 'localhost',
	'username' => 'root',
	'password' => '',
	'database' => 'autocomlete_db', 
	'dbdriver' => 'mysqli',
	'dbprefix' => '',
	'pconnect' => FALSE,
	'db_debug' => (ENVIRONMENT !== 'production'),
	'cache_on' => FALSE,
	'cachedir' => '',
	'char_set' => 'utf8',
	'dbcollat' => 'utf8_general_ci',
	'swap_pre' => '',
	'encrypt' => FALSE,
	'compress' => FALSE,
	'stricton' => FALSE,
	'failover' => array(),
	'save_queries' => TRUE
);

 

Step 5. Controller

Go ahead and create a controller file controllers/Blog.php with the following this code:

<?php
class Blog extends CI_Controller{
	function __construct(){
		parent::__construct();
		$this->load->model('blog_model');
	}

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

	function get_autocomplete(){
		if (isset($_GET['term'])) {
		  	$result = $this->blog_model->search_blog($_GET['term']);
		   	if (count($result) > 0) {
		    foreach ($result as $row)
		     	$arr_result[] = $row->blog_title;
		     	echo json_encode($arr_result);
		   	}
		}
	}

}

 

Step 6. Model

Go ahead and create a model file models/Blog_model.php with the following this code:

<?php
class Blog_model extends CI_Model{

	function search_blog($title){
		$this->db->like('blog_title', $title , 'both');
		$this->db->order_by('blog_title', 'ASC');
		$this->db->limit(10);
		return $this->db->get('blog')->result();
	}

}

 

Step 7. View

Go ahead and create a view file views/blog_view.php with the following this code:

<!DOCTYPE html>
<html>
<head>
	<meta charset="utf-8">
    <meta name="viewport" content="width=device-width, initial-scale=1, shrink-to-fit=no">
	<title>Autocomplete</title>
	<link rel="stylesheet" href="<?php echo base_url().'assets/css/bootstrap.css'?>">
	<link rel="stylesheet" href="<?php echo base_url().'assets/css/jquery-ui.css'?>">
</head>
<body>
	<div class="container">
		<div class="row">
			<h2>Autocomplete Codeigniter</h2>
		</div>
		<div class="row">
			<form>
				 <div class="form-group">
				    <label>Title</label>
				    <input type="text" class="form-control" id="title" placeholder="Title" style="width:500px;">
				  </div>
			</form>
		</div>
	</div>

	<script src="<?php echo base_url().'assets/js/jquery-3.3.1.js'?>" type="text/javascript"></script>
	<script src="<?php echo base_url().'assets/js/bootstrap.js'?>" type="text/javascript"></script>
	<script src="<?php echo base_url().'assets/js/jquery-ui.js'?>" type="text/javascript"></script>
	<script type="text/javascript">
		$(document).ready(function(){
			$( "#title" ).autocomplete({
		      source: "<?php echo site_url('blog/get_autocomplete/?');?>"
		    });
		});
	</script>

</body>
</html>

 

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:

Final Result

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:

Autocomplete Dropdown

When one option of autocomplete is selected, it will show the other related fields. Like this:

Autocomplete Dropdown Result

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:

function get_autocomplete(){
	if (isset($_GET['term'])) {
	  	$result = $this->blog_model->search_blog($_GET['term']);
	   	if (count($result) > 0) {
		    foreach ($result as $row)
		     	$arr_result[] = array(
					'label'			=> $row->blog_title,
					'description'	=> $row->blog_description,
			 );
		     	echo json_encode($arr_result);
	   	}
	}
}

After that, open view blog_view.php, and then change to be like this:

<!DOCTYPE html>
<html>
<head>
	<meta charset="utf-8">
    <meta name="viewport" content="width=device-width, initial-scale=1, shrink-to-fit=no">
	<title>Autocomplete</title>
	<link rel="stylesheet" href="<?php echo base_url().'assets/css/bootstrap.css'?>">
	<link rel="stylesheet" href="<?php echo base_url().'assets/css/jquery-ui.css'?>">
</head>
<body>
	<div class="container">
		<div class="row">
			<h2>Autocomplete Codeigniter</h2>
		</div>
		<div class="row">
			<form>
				 <div class="form-group">
				    <label>Title</label>
				    <input type="text" name="title" class="form-control" id="title" placeholder="Title" style="width:500px;">
				 </div>
				 <div class="form-group">
				    <label>Description</label>
				    <textarea name="description" class="form-control" placeholder="Description" style="width:500px;"></textarea>
				 </div>
			</form>
		</div>
	</div>

	<script src="<?php echo base_url().'assets/js/jquery-3.3.1.js'?>" type="text/javascript"></script>
	<script src="<?php echo base_url().'assets/js/bootstrap.js'?>" type="text/javascript"></script>
	<script src="<?php echo base_url().'assets/js/jquery-ui.js'?>" type="text/javascript"></script>
	<script type="text/javascript">
		$(document).ready(function(){

		    $('#title').autocomplete({
                source: "<?php echo site_url('blog/get_autocomplete');?>",
     
                select: function (event, ui) {
                    $('[name="title"]').val(ui.item.label); 
                    $('[name="description"]').val(ui.item.description); 
                }
            });

		});
	</script>

</body>
</html>

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:

<?php
class Tutorial extends CI_Controller{
	function __construct(){
		parent::__construct();
		$this->load->model('blog_model');
		error_reporting(0);
	}

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

	function get_autocomplete(){
		if (isset($_GET['term'])) {
		  	$result = $this->blog_model->search_blog($_GET['term']);
		   	if (count($result) > 0) {
		    foreach ($result as $row)
		     	$arr_result[] = array(
					'label'	=> $row->blog_title,
				);
		     	echo json_encode($arr_result);
		   	}
		}
	}

	function search(){
		$title=$this->input->get('title');
		$data['data']=$this->blog_model->search_blog($title);

		$this->load->view('search_view',$data);
	}

}

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:

<!DOCTYPE html>
<html>
<head>
	<meta charset="utf-8">
    <meta name="viewport" content="width=device-width, initial-scale=1, shrink-to-fit=no">
	<title>Autocomplete</title>
	<link rel="stylesheet" href="<?php echo base_url().'assets/css/bootstrap.css'?>">
	<link rel="stylesheet" href="<?php echo base_url().'assets/css/jquery-ui.css'?>">
</head>
<body>
	<div class="container">
		<div class="row">
			<h2>Search</h2>
		</div>
		<div class="row">
			<form id="form_search" action="<?php echo site_url('tutorial/search');?>" method="GET">
				 <div class="input-group">
				    <input type="text" name="title" class="form-control" id="title" placeholder="Title" style="width:500px;">
				    <span class="input-group-btn">
				        <button class="btn btn-info" type="submit">Search</button>
				    </span>
				 </div>
			</form>
		</div>
	</div>

	<script src="<?php echo base_url().'assets/js/jquery-3.3.1.js'?>" type="text/javascript"></script>
	<script src="<?php echo base_url().'assets/js/bootstrap.js'?>" type="text/javascript"></script>
	<script src="<?php echo base_url().'assets/js/jquery-ui.js'?>" type="text/javascript"></script>
	<script type="text/javascript">
		$(document).ready(function(){

		    $('#title').autocomplete({
                source: "<?php echo site_url('tutorial/get_autocomplete');?>",
     
                select: function (event, ui) {
                    $(this).val(ui.item.label);
                    $("#form_search").submit(); 
                }
            });

		});
	</script>

</body>
</html>

After that, create the view again and give name search_view.php with code as follows:

<!DOCTYPE html>
<html>
<head>
	<meta charset="utf-8">
    <meta name="viewport" content="width=device-width, initial-scale=1, shrink-to-fit=no">
	<title>Search Result</title>
	<link rel="stylesheet" href="<?php echo base_url().'assets/css/bootstrap.css'?>">
</head>
<body>
	<div class="container">
		<div class="row">
			<h2>Search Result</h2>
		</div>
		<div class="row">
			<table class="table table-striped">
				<thead>
					<tr>
						<th>Title</th>
						<th>Description</th>
					</tr>
				</thead>
				<tbody>
				<?php foreach($data as $row):?>
					<tr>
						<td><?php echo $row->blog_title;?></td>
						<td><?php echo $row->blog_description;?></td>
					</tr>
				<?php endforeach;?>
				</tbody>
			</table>
		</div>
	</div>

	<script src="<?php echo base_url().'assets/js/jquery-3.3.1.js'?>" type="text/javascript"></script>
	<script src="<?php echo base_url().'assets/js/bootstrap.js'?>" type="text/javascript"></script>

</body>
</html>

Done.

Now, please visit the URL http://localhost/autocomplete/index.php/tutorial for testing.

If it goes well, it will look like this:

Search Autocomplete

Type in the keyword "codeigniter" then it will look like this:

Autocomplete Auto Submit

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:

Search Result

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.

Download Source

Share:



Sponsorship:

Comments (6)

Shambhu Nath Paul, 25 May 2018 09:14 -

yes, you have done it. Thank you.

M Fikri, 22 July 2018 08:49 -

You are welcome.

Brian, 19 June 2018 20:26 -

Excellent tutorial simple and to the point. Now sir how can you count rows of a table in code igniter.Kind regards. Brian

M Fikri, 22 July 2018 08:55 -

For that case, I usually use num_rows() method. But if you mean give number for a table like 1,2,3,4,5,etc. You can using looping method for that case.
Thank you for asking.

Yaya DEMBELE, 12 August 2018 18:33 -

Je vous écris en français car je ne suis pas très en anglais mais je me suis quand même débrouller à comprendre à ce que vous avez dit dans le tutoriel. Je vous remercie vraiment car vous m'avez beaucoup aidé avec ce tutoriel. Le code est très simple facile à comprendre pour un amateur comme moi vous l'art de faire les choses comme il se doit. Merci encore

M Fikri, 13 August 2018 09:59 -

You're welcome.

Leave a Comment