Welcome Guest, Not a member yet? Register   Sign In
Codeigniter - Autocomplete with Jquery (small article)
#1

[eluser]J. Brenne[/eluser]
Hey,
i just wrote a small article about creating autocomplete with codeiginter and jquery.
It's based on the Jquery Autocomplete Plugin of Bassistance.de. I searched a while for a working autocomplete and only found some old or bad tutorials or expliantions. So I testet around and found a way to realize it with reading from databse. I used MySQL for that.
Thats why I wrote this article.


If you want to see the original and with a complete ZIP download - can be found at:
http://allover.worldattack.de/2009/01/25...th-jquery/

Lets start.
You need for the the view:
Code:
$(function() {
    function format(mail) {
        return mail.name + " (" + mail.to + ")";
    }

    $("#name").autocomplete('autocomplete/get_Names', {
        multiple: false,
        parse: function(data) {
            return $.map(eval(data), function(row) {
                return {
                    data: row,
                    value: row.name,
                    result: row.name
                }
            });
        },
        formatItem: function(item) {
            return format(item);
        }
    });
});

The controller:
Code:
class Autocomplete extends Controller {

    function Autocomplete()
    {
        parent::Controller();    

        // load models
        $this->load->model('autocomplete_model');
    }

    function index()
    {
        $this->load->view('autocomplete', array());
    }

    function get_Names()
    {
        $q = strtolower($_POST["q"]);
        if (!$q) return;

        // form dropdown and myql get countries
        $airports = $this->autocomplete_model->getData();

        // go foreach
        foreach($airports->result() as $airport)
        {
            $items[$airport->callname] = $airport->country;
        }

        echo "[";
        foreach ($items as $key=>$value) {
            if (strpos(strtolower($key), $q) !== false) {
                echo "{ name: \"$key\", to: \"$value\" }, ";
            }
        }
        echo "]";
    }
}

Now the model/autocomplete_model.php
Code:
class Autocomplete_model extends Model
{
    function Autocomplete_model()
    {
        parent::Model();
    }
    function getData()
    {
        $this->db->select('*')->from('airports');
        $query = $this->db->get();
        return $query;
    }
}

jquery.autocomplete.js
The last thing is, you have to change the jquery.autocomplete.js into POST.
So just — add type: “post”, –. That’s all!
Code:
$.ajax({
// try to leverage ajaxQueue plugin to abort previous requests
type: "post", // add this only! must be line ~340
mode: "abort",
// limit abortion to this input
port: "autocomplete" + input.name,
dataType: options.dataType,
url: options.url,
data: $.extend({
    q: lastWord(term),
    limit: options.max
}, extraParams),
success: function(data) {
    var parsed = options.parse && options.parse(data) || parse(data);
    cache.add(term, parsed);
    success(term, parsed);
}
});

Thats all hope it was useful and sorry for my bad english. If you have any question - ask.
#2

[eluser]Ssendol[/eluser]
Thanks lot, this is what I looking.
Don't you have any demo and/or can you post DB ?
I tried to use my onw DB, but not work.
Thanks
#3

[eluser]J. Brenne[/eluser]
Code:
// go foreach
        foreach($airports->result() as $airport)
        {
            $items[$airport->callname] = $airport->country;
        }

The tablenames were callname and country. Test it. Have to work Wink
#4

[eluser]Ssendol[/eluser]
Thanks, I made a DB and tried again, but still not working.
Sometimes 'Object expected' javascript error coming as '$(function() {'

I added <script type="text/javascript" ... in _autocomplete.php all of js file of course.
I think I miss something, but I have no idea.
I am sorry to bother you, but I am too new about.

Thank you again.
#5

[eluser]J. Brenne[/eluser]
Kk here is there orginal script.. or a part of it.
Load the javascript in your header. My Header looks like
Code:
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
&lt;html &gt;
&lt;head&gt;
    &lt;title&gt;&lt;?=$title;?&gt;&lt;/title&gt;
    &lt;meta http-equiv="content-type" content="text/html; charset=utf-8" /&gt;
    &lt;link rel="stylesheet" href="&lt;?=base_url();?&gt;css/common.css" type="text/css" /&gt;
    &lt;link rel="stylesheet" href="&lt;?=base_url();?&gt;css/thickbox.css" type="text/css" /&gt;
    [removed][removed]
    [removed][removed]
    [removed][removed]
    [removed][removed]
    [removed][removed]
&lt;/head&gt;

My controller looks like:
Code:
function json_name()
    {
        $q = strtolower($_POST["q"]);
        if (!$q) return;
        
        // form dropdown and myql get countries
        $countries = $this->map_model->getCountries();
        foreach($countries->result() as $country)
        {
            $items[$country->name] = $country->countryCode;
        }
        
        echo "[";
        foreach ($items as $key=>$value) {
            if (strpos(strtolower($key), $q) !== false) {
                echo "{ name: \"$key\", to: \"$value\" }, ";
            }
        }
        echo "]";
    }

view
[code]
[removed]
$(function() {
function format(mail) {
return mail.name + " (" + mail.to + ")";
}

$("#airport_name").autocomplete('airport/json_name', {
multiple: false,
parse: function(data) {
return $.map(eval(data), function(row) {
return {
data: row,
value: row.name,
result: row.name
}
});
},
formatItem: function(item) {
return format(item);
}
});
});
[removed]
[code]
#6

[eluser]Skuja[/eluser]
I would like to note that you should run xss_clean check for $_POST data:
Code:
use
$q = $this->input->post('q',TRUE);
instead of
$q = strtolower($_POST["q"]);
#7

[eluser]Ssendol[/eluser]
Thank you for help.
I checked line by line, but I can't find anything wrong.
Anyway, javascript error came randomly as '; required' or 'name is null or'...
I gave up ! :-S
I must miss something, thank you again.
#8

[eluser]Ssendol[/eluser]
It works with Chrome 1.0.154.46 and Firefox 3.0.5, but it not work IE 7(7.5730.13)
OS is Window XP Pro SP3.
Any idea ?
Thanks.
#9

[eluser]J. Brenne[/eluser]
I cant give you support to the js autocomplete. Its just jquery with a plugin. I only deisgned the controller and view.
But no sorry I dont have a idea.
#10

[eluser]Unknown[/eluser]
thanks brenne...
but how can i passing extraParameters..?




Theme © iAndrew 2016 - Forum software by © MyBB