Before you read this, i hope you understand about codeigniter directory structure, URLs, jquery (just the basic) and PHP.

I’ve developed a jquery autocomplete in php, from here, to codeigniter in my own version. I never change the jqueries, CSSs, etc. I just implemented it into codeigniter.

Here is:

the Model

<?php
class Automodel extends Model{
function Automodel()
{
parent::Model();
}

function get_country($string)
{
$this->db->select(‘value’)->from(‘countries’)->like(‘value’,$string)->limit(10);
return $this->db->get()->result();
}
}
?>

The View named with template.php

<!DOCTYPE html PUBLIC “-//W3C//DTD XHTML 1.0 Transitional//EN” “http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd”>
<html xmlns=”http://www.w3.org/1999/xhtml”>

<head>
<meta http-equiv=”Content-Type” content=”text/html; charset=utf-8″ />
<title>Ajax Auto Suggest</title>

<script type=”text/javascript” src=”<?php echo base_url().”js/jquery-1.2.1.pack.js”?>”></script>
<script type=”text/javascript”>
function lookup(inputString) {
if(inputString.length == 0) {
// Hide the suggestion box.
$(‘#suggestions’).hide();
} else {
$.post(“http://localhost/ori/index.php/service/exists”, {a: “”+inputString+”"},
function(data){

if(data.length >0) {
$(‘#suggestions’).show();
$(‘#autoSuggestionsList’).html(data);
}
});
}
} // lookup

function fill(thisValue) {
$(‘#inputString’).val(thisValue);
setTimeout(“$(‘#suggestions’).hide();”, 200);
}
</script>

<style type=”text/css”>
body {
font-family: Helvetica;
font-size: 11px;
color: #000;
}

h3 {
margin: 0px;
padding: 0px;
}

.suggestionsBox {
position: relative;
left: 30px;
margin: 10px 0px 0px 0px;
width: 200px;
background-color: #212427;
-moz-border-radius: 7px;
-webkit-border-radius: 7px;
border: 2px solid #000;
color: #fff;
}

.suggestionList {
margin: 0px;
padding: 0px;
}

.suggestionList li {

margin: 0px 0px 3px 0px;
padding: 3px;
cursor: pointer;
}

.suggestionList li:hover {
background-color: #659CD8;
}
</style>

</head>

<body>
<div>
<form >
<div>
Type your county:
<br />
<input type=”text” size=”30″ value=”" id=”inputString” onkeyup=”lookup(this.value);” onblur=”fill();” />
</div>

<div id=”suggestions” style=”display: none;”>
<img src=”<?php echo base_url().”images/upArrow.png”?>” style=”position: relative; top: -12px; left: 30px;” alt=”upArrow” />
<div id=”autoSuggestionsList”>
&nbsp;
</div>
</div>
</form>
</div>

</body>
</html>

The Controller

<?php
class Service extends Controller
{
function Service()
{
parent::Controller();
}

function index()
{
redirect(‘service/view’);
}

function view()
{
$this->load->view(‘template’);
}

function exists()
{
$this->load->model(‘automodel’,'am’);

$query = $this->am->get_country($_POST['a']);
foreach($query as $row){
echo ‘<li onClick=”fill(\”.$row->value.’\');”>’.$row->value.’</li>’;
}

}
}
?>