Search AutoComplete using Codeigniter jQuery

Introduction

Here in Codeigniter jQuery AutoComplete example we will see how to do search AutoComplete using Codeigniter jQuery.  Autocomplete allows you to easily create autocomplete and auto-suggest boxes for text input fields. When you start a search on Google or other search engines, you can find the information you are looking for using search predictions. Search predictions are possible search terms you can use that are related to the terms you are typing and what other people are searching for.

Autocomplete is a feature in which an application predicts the rest of a word a user is typing. In graphical user interfaces, users can typically press the tab key to accept a suggestion or the down arrow key to accept one of several.

Autocomplete speeds up human-computer interactions when it correctly predicts the word a user intends to enter after only a few characters have been typed into a text input field. The autocomplete is a normal text input enhanced by a panel of suggested options.

Prerequisites

Knowledge of HTML, JavaScript
Knowledge of PHP, Codeigniter 3.1

Final Output

Here is the below picture of the final output on the browser

codeigniter autocomplete

Example with Source Code

In this example we will create a project root directory called ci3 and copy all the required Codeigniter 3 files.

Create below model class in order to provide data to the controller. The actual data should come from database or any other persistent sources.

<?php

if (!defined('BASEPATH'))
	exit('No direct script access allowed');
	
/**
* Description of Data_model
*
* @author https://roytuts.com
*/

class Data_model extends CI_Model {		
		
		function get_data($search_term) {
			$arr = array(
				"Lorem Ipsum is simply dummy text of the printing and typesetting",
				"Lorem Ipsum has been the industry's standard dummy",
				"nd scrambled it to make a type specimen book. It",
				"typesetting, remaining essentially unchanged. It ",
				"sum passages, and more recently with desktop publi",
				"Contrary to popular belief, Lorem Ipsum is not sim",
				"professor at Hampden-Sydney College in Virginia, looked up one",
				"passage, and going through the cites of the word in",
				"comes from sections 1.10.32 and 1.10.33 of 'de Finibus Bonorum",
				"BC. This book is a treatise on the theory of ethics, very popu",
				"here are many variations of passages of Lorem Ipsum availa",
				"believable. If you are going to use a passage of Lorem Ips",
				"middle of text. All the Lorem Ipsum generators on the Intern",
				"tend to repeat predefined chunks as necessary, making this the",
				"first true generator on the Internet. It uses a dictionary of over 20",
				"he standard chunk of Lorem Ipsum used since the 1500s i",
				"1.10.33 from 'de Finibus Bonorum et Malorum' by Cicero are als",
				"reproduced in their exact original form, accompanied by English",
				"eadable content of a page when looking at its layout. The point"
			);

			$filteredArray = array_filter($arr, function($element) use($search_term){
				return isset($element) && strpos($element, $search_term) !== false;
			});
			
			return $filteredArray;
		}
}

/* End of file data_model.php */
/* Location: ./application/models/data_model.php */

The above model class Data_Model is written into Data_Model.php file under ci3/application/models directory. In the above model class I have used dummy text and in real application the data should come from actual data sources.

Create below controller class which will handle the request and response between client and server. The below class Search is written into Search.php file under ci3/application/controllers directory.

<?php

if (!defined('BASEPATH'))
	exit('No direct script access allowed');

/**
* Description of Search
*
* @author https://roytuts.com
*/

class Search extends CI_Controller {
	
	function __construct() {
		parent::__construct();
		$this->load->model('data_model');
	}
	
	public function index() {
		$this->load->view('autocomplete');
	}
	
	function search_results() {
		if (isset($_REQUEST['q'])) {
			$results = $this->data_model->get_data($_REQUEST['q']);
			echo json_encode($results);
		}
	}
	
}

/* End of file Search.php */
/* Location: ./application/controllers/Search.php */

Now we need to display data on the browser so we will create below view file called autocomplete.php under ci3/application/views directory.

<!DOCTYPE html>
<html>
<head>
	<meta http-equiv="Content-Type" content="text/html; charset=ISO-8859-1" />
	<meta name="viewport" content="width=device-width, initial-scale=1">
	<title>Codeigniter Auto-Complete using jQuery</title>
	<link rel="stylesheet" href="//code.jquery.com/ui/1.12.1/themes/base/jquery-ui.css">
	<link rel="stylesheet" href="<?php echo assets_url(); ?>assets/css/style.css">
	<style>
	.ui-autocomplete-loading {
		background: white url("<?php echo assets_url(); ?>assets/images/ui-anim_basic_16x16.gif") right center no-repeat;
	}
	</style>
	<script src="https://code.jquery.com/jquery-1.12.4.js"></script>
	<script src="https://code.jquery.com/ui/1.12.1/jquery-ui.js"></script>
	<script>
		$(function() {
			$("#searchBox").autocomplete({
				source : function(request, response) {
					$.ajax({
						//type: "GET",
						url : "http://localhost/ci3/index.php/search/search_results",
						dataType : "json",
						cache: false,
						data : {
							q : request.term
						},
						success : function(data) {
							//alert(data);
							//console.log(data);
							response(data);
						},
						error: function(jqXHR, textStatus, errorThrown) {
							console.log(textStatus+" "+errorThrown);
						}
					});
				},
				minLength : 2
			});
		});
	</script>
</head>
<body>
	<div style="width: 600px; margin: auto;">
		<h3>Codeigniter Auto-Complete using jQuery</h3>
		<fieldset>
			<legend>Search Here</legend>
			<p>
				<input type="text" name="search" id="searchBox" style="width: 560px; margin: auto;" />
			</p>
		</fieldset>
	</div>
</body>
</html>

You need to add one local css, image files. So download here those files and put the assets directory under root directory of the project ci3.

assets

Now we need to work on config part otherwise application will throw some errors at runtime.

You may like to read the similar tutorial on Search AutoComplete using Spring and jQuery

Create below asset helper function which will help us to load local static resource files such as css, js, images etc because we cannot directly load those files in Codeigniter.

<?php

if (!defined('BASEPATH'))
	exit('No direct script access allowed');

function assets_url() {
	return base_url();
}

/* End of file assets_helper.php */
/* Location: ./application/helpers/assets_helper.php */

Now autoload few things in order to avoid loading everytime. This has to be modified in ci3/application/config/autoload.php file.

$autoload['helper'] = array('url', 'file', 'text', 'form', 'assets');

Now update the default controller in ci3/application/config/routes.php file

$route['default_controller'] = 'search';

Now run the application and verify you are getting the desired output.

Source Code

here

Please make sure to rename the folder ci3_autocomplete to ci3.

Thanks for reading.

Leave a Reply

Your email address will not be published. Required fields are marked *