jQuery UI Autocomplete in CodeIgniter with Database

autocomplete_featured

In this tutorial I will show you how to connect jQuery UI Autocomplete plugin to remote datasource (eg. database table) with CodeIgniter. I have noticed that many people were asking about this and after searching the Internet for hours, I couldn’t actually find a complete tutorial that teaches you how to do this. So, without further ado, let’s get to work. To get this really useful plugin up and running, we will need to:

  1. Download the plugin from the jQuery UI website.
  2. Link to the JavaScript and CSS files in our HTML
  3. Create a database table with some data
  4. Create a CodeIgniter View to hold the textbox to query the database
  5. Create a CodeIgniter Model
  6. Create a CodeIgniter Controller
  7. Apply the autocomplete function to the textbox using jQuery

If you would like to display an image with the autocomplete list (like the search box at IMDB) please visit my other tutorial jQuery UI Autocomplete in CodeIgniter with Images and Database.

The code in this tutorial works perfectly and if you follow the tutorial step by step you should have no problem.

1- Downloading jQuery UI Autocomplete plugin

You can download the jQuery UI Autocomplete plugin from the jQuery UI main website.

2- Linking to the JavaScript and CSS files

After downloading the plugin we first need to go to the head section of your main index file and:

  • Link to a CSS file that comes with the plugin
  • Link to the jQuery library
  • Link to the jQuery UI library
<link href="link/to/jquery.ui.css" rel="stylesheet" type="text/css" />

 

<script type="text/javascript" src="link/to/jquery.js"></script>
<script type="text/javascript" src="link/to/jquery.ui.js"></script>
Note: You can also use the minified version of the plugin if you like.

3- Database table

For the sake of this tutorial I have created a database table called birds ad it stores the bird type/name and an (also known as) aka value.

CREATE TABLE  birds (
	id INT NOT NULL AUTO_INCREMENT,
	bird VARCHAR(50),
	aka VARCHAR(50),
	PRIMARY KEY (id)
	) ENGINE = MYISAM ;

Go on and insert some data

INSERT INTO birds (id, bird, aka) VALUES
(1, "Great Bittern", "Botaurus stellaris"),
(2, "Little Grebe", "Tachybaptus ruficollis"),
(3, "Black-necked Grebe", "Podiceps nigricollis"),
(4, "Little Bittern", "Ixobrychus minutus"),
(5, "Black-crowned Night Heron", "Nycticorax nycticorax"),
(6, "Purple Heron", "Ardea purpurea"),
(7, "White Stork", "Ciconia ciconia"),
(8, "Spoonbill", "Platalea leucorodia"),
(9, "Red-crested Pochard", "Netta rufina"),
(10, "Common Eider", "Somateria mollissima"),
(11, "Red Kite", "Milvus milvus"),
(12, "Hen Harrier", "Circus cyaneus"),
(13, "Montagu's Harrier", "Circus pygargus"),
(14, "Black Grouse", "Tetrao tetrix"),
(15, "Grey Partridge", "Perdix perdix"),
(16, "Spotted Crake", "Porzana porzana"),
(17, "Corncrake", "Crex crex"),
(18, "Common Crane", "Grus grus"),
(19, "Avocet", "Recurvirostra avosetta"),
(20, "Stone Curlew", "Burhinus oedicnemus");

4- CodeIgniter View (birds_view.php) and Textbox

In your CodeIgniter project go on and create a view and name it birds_view.php then save it in the views folder. We need this view to hold the textbox that will take input and query the database. Make sure you give this textbox a unique id so it can be attached to the autocomplete event later. As we are going to use the birds data used by the jQuery UI, we will give the textbox an id of birds. In your view page just add the following line of HTML.

<input type="text" id="birds" />

5- CodeIgniter Model (birds_model.php)

In your CodeIgniter project go on and create a model and name it birds_model.php

The plugin expects the data to be in one of two forms:
1- An Array of Strings:
[ “Choice1”, “Choice2”, … ]
2- An Array of Objects with label and value properties:
[ { label: “Choice1”, value: “value1” }, … ]
The label property is displayed in the suggestion menu. The value will be inserted into the input element after the user selected something from the menu. If just one property is specified, it will be used for both, eg. if you provide only value-properties, the value will also be used as the label.

To show you how to produce any of the two data forms shown above, I have included two versions of the birds_model.php

Outputs an Array of Strings

<?php
//birds_model.php (Array of Strings)
class Birds_model extends CI_Model{
	function get_bird($q){
		$this->db->select('bird');
		$this->db->like('bird', $q);
		$query = $this->db->get('birds');
		if($query->num_rows() > 0){
			foreach ($query->result_array() as $row){
				$row_set[] = htmlentities(stripslashes($row['bird'])); //build an array
			}
			echo json_encode($row_set); //format the array into json data
		}
	}
}

Outputs:
[ “Great Bittern”,”Little Grebe”, … ]

Outputs an Array of Objects

<?php
//birds_model.php (Array of Objects)
class Birds_model extends CI_Model{
	function get_bird($q){
		$this->db->select('*');
		$this->db->like('bird', $q);
		$query = $this->db->get('birds');
		if($query->num_rows() > 0){
			foreach ($query->result_array() as $row){
				$new_row['label']=htmlentities(stripslashes($row['bird']));
				$new_row['value']=htmlentities(stripslashes($row['aka']));
				$row_set[] = $new_row; //build an array
			}
			echo json_encode($row_set); //format the array into json data
		}
	}
}

Outputs:
[ { label: “Great Bittern”, value: “Botaurus stellaris” },{ label: “Little Grebe”, value: “Tachybaptus ruficollis” }, … ]

6- CodeIgniter Controller (birds.php)

The controller expects query letter or word using the GET method and then passes it to the birds_model through the get_bird function.

<?Php
//birds.php
class Birds extends CI_Controller{
	function index(){
		$this->load->view('birds_view');
	}

	function get_birds(){
		$this->load->model('birds_model');
		if (isset($_GET['term'])){
			$q = strtolower($_GET['term']);
			$this->birds_model->get_bird($q);
		}
	}
}

7- jQuery code

Finally, we have to tell the jQuery which textbox we need to use for the autocomplete plugin and also we have to specify our data source by giving the path to the controller and method (birds/get_birds) that handle the data retrieval.

$(function(){
	$("#birds").autocomplete({
		source: "birds/get_birds" // path to the get_birds method
	});
});

The function autocomplete has more options such as minLength, delay, autoFocus, postion, visit the plugin website to find out more about them.

As for the jQuery code you have two options either to directly include it in the head section of your index page between script tags or place it in a new file and call it main.js for example and then link to it as follows:

<script type="text/javascript" src="link/to/main.js"></script>
For the Ajax loading image to appear make sure you include the following in your “jquery.ui.autocomplete.css” file.
.ui-autocomplete-loading {
	background: #fff url('../link/to/ajax-loading-image') right center no-repeat !important;
}

If this tutorial was helpful to you please let me know, by leaving a comment.

If you have any questions or would like me to discuss a certain topic please send me a message or simply just leave a comment below!

jQuery UI Autocomplete in CodeIgniter with Database
57 votes, 4.14 avg. rating (82% score)
  • Posted in: CodeIgniter
Husamaldin Tayeh

Posted by

Husamaldin is a computer programmer, blogger, entrepreneur and an overall thinker. He is the founder and editor of Coders Mount. He loves everything about computers and programming. Find out more about him here or follow him on Twitter Google+ | LinkedIn.

  • http://www.facebook.com/havurgiray Giray Havur

    Thank you! It was to the point and useful.

  • Abdullah

    very well!

  • David

    This is awesome, thanks a lot.

    • amit

      sdgvsdgb @disqus_F42OV2B0jv:disqus fdsgbvdfb @

  • WallyJ

    In step 2 and 3 you do not mention where to put the link and script codes, or the input box (which files to put them in), though the input box certainly suggests it goes in a view file. For newbs like me, this would be helpful. :)

    The same is true for the jquery code in step 7. Not sure where to put this.

    Otherwise this tutorial is wonderful and is exactly what I was looking for. Thanks!!

    • http://www.codersmount.com/ Husamaldin Tayeh

      Thanks for the valuable feedback. I will update the post soon. Glad you found it helpful.

    • WallyJ

      I figured out that part of my problem was a jquery conflict, so after investigating the error, I got rid of the error by changing the model to use the “jQuery(document).ready(function($){” syntax.

      However, now my text box does nothing, but the console in Chrome Web Developer shows no errors. So I am playing with the code in my model to see if there is something that I did wrong there. Again, all help is appreciated.

    • http://www.codersmount.com/ Husamaldin Tayeh

      To include the jQuery code you have two options either to directly include it in the section of your index page or place it in a new file and call it main.js for example and then link to it using the tag. You shouldn’t include any jQuery in your model. I hope this helps.

    • WallyJ

      Thanks for the edit and the tip. I am close now, though I am now getting an error that says:

      Message: Undefined index: term

      Filename: controllers/birds.php

      I didn’t really understand what “term” was referring to anyway… Thanks again for your help.

    • http://www.codersmount.com/ Husamaldin Tayeh

      The value in $_GET[‘term’] is set by the UI plugin and it holds the value of the textbox.

    • WallyJ

      Ok. That makes sense, though I’m not sure how it knows which text box to get the value from if there is more than one.

      I put the function inside a tag in the head of my view.

      I also added some text and the input box to the view as well.

      The text and the text box show on the page, but this appears at the top of the page:

      [“Great Bittern”,”Little Grebe”,”Black-necked Grebe”,”Little Bittern”,”Black-crowned Night Heron”,”Purple Heron”,”White Stork”,”Spoonbill”,”Red-crested Pochard”,”Common Eider”,”Red Kite”,”Hen Harrier”,”Montagu’s Harrier”,”Black Grouse”,”Grey Partridge”,”Spotted Crake”,”Corncrake”,”Common Crane”,”Avocet”,”Stone Curlew”]

      Which looks like the data pulled by the function.

      The text box does not perform an autocomplete.

      I feel like I am so close, but can’t figure it out.

    • http://www.codersmount.com/ Husamaldin Tayeh

      Ok, that’s good. Now make sure that you have the correct path to the jquery.ui.css file as well as the jquery.js and jquery.ui.js.

      Also make sure that your input field (textbox) has a unique id, in the tutorial I have given it the id of birds, this id is very important for the jQuery to know which textbox to bind to. Do this and let me know what happens.

      This tutorial is fully tested to be working with no problems so if you follow each step carefully your code is guaranteed to work.

    • WallyJ

      I used “birds” just like you did.

      And your code does not load a view. I am supposed to add that right? So I don’t understand how just using your code will work.

      I did change the references to the js and css files to point to the live ones:

      These all show as loading properly in Firebug.

      I am using the exact db fields and names you prescribed, which is why my data is the same. It is just showing incorrectly.

      You instructions say to put the jquery code into the head section. Do we need to put it within tags?

    • http://www.codersmount.com/ Husamaldin Tayeh

      Yes of course your jQuery code should go between ….jQuery code here …..

    • http://www.codersmount.com/ Husamaldin Tayeh

      Ok, in your controller file (birds.php) change this $q = strtolower($this->input->get()); to:
      $q = strtolower($this->input->get(‘term’)); or $q = strtolower($_GET[‘term’]);

      Let me know what hapenes

    • WallyJ

      I received this error message:

      A PHP Error was encountered

      Severity: Notice

      Message: Undefined index: term

      Filename: controllers/birds.php

      Line Number: 7

      It also still shows the results of the query on the page.

      Thanks again for your help…

    • http://www.codersmount.com/ Husamaldin Tayeh

      Ok, let me have a look at the code again, and try to test it on different versions of jQuery UI and see what’s wrong.

    • http://www.codersmount.com/ Husamaldin Tayeh

      Well, the “Message: Undefined index: term” is fixed now. Refere to the new modified controller code.

      This is really weird, firebug shows that the request is successful but the autocomplete list is now showing. I will try to figure it out. This was working perfectly before.

    • WallyJ

      Thanks again for your help. Did you come up with anything?

    • http://www.codersmount.com/ Husamaldin Tayeh

      If you have noticed, the correct data is being returned along with the page HTML tags and that what is causing the problem. I am trying to find a solution.

    • http://www.codersmount.com/ Husamaldin Tayeh

      Hi Wally,
      Sorry for not replying any sooner as I am extremely busy with university stuff. Our friend Andres was kind enough to point us to the error. I have now updated the post with the working solution. The code is now tested and is working perfectly.

    • lepotier

      Hi,
      I have the same problem, a solution?

    • http://www.codersmount.com/ Husamaldin Tayeh

      If you follow this tutorial you should get it working. This issue was resolved and the code was updated. But if you still can not get this to work, then please send me the code of your controller so I can help.

    • WallyJ

      Were you able to come up with a solution for the autocomplete?

      Thanks again for your help.

  • jonnelabuan

    Hi Husamaldin, thanks for this! I’m a little newb using CodeIgniter framework and I don’t know how to use it. However, what if I didn’t download the plugin, and I just link directly to Jquery site like this:

    Did it work?

    • http://www.codersmount.com/ Husamaldin Tayeh

      Yes, that should work.

    • jonnelabuan

      Well done.. Thanks

  • Andrés Igualada

    Thanks, a very useful post, but I also have the problem with the population list, like other people stated above. I think I’ve found a solution, I’ll let you know in a few minutes!

    • http://www.codersmount.com/ Husamaldin Tayeh

      That would be great Andres, since I am really busy these days and I didn’t have the time to look into this problem. It is really weird because I tested this code and it was working perfectly. I guess the problem is related to the view, because the firebug console shows that the correct data is being returned along with the page HTML tags and I think the HTML tags are what causing the autocomplete from not showing.

    • Andrés Igualada

      Here is the solution that works for me:

      1.- Separate between functions inside the controller. Keep “index” just for loading the views.

      2.- Create a new method called get_birds() inside the controller:

      public function get_birds() {
      if (!isset($_GET[‘term’])){
      exit;
      }

      $this->load->model(‘birds_model’);
      $q = strtolower($_GET[‘term’]);
      $this->birds_model->get_birds($q);
      }

      3.- Modify the jquery call:

      $(function(){
      $(“#birds”).autocomplete({
      source: “birds/get_birds” // name of controller AND the search function
      });
      });

      This way works for me. The problem was that if you attach the function that calls the database along with the views, everytime you make a new search, the views are triggered again, so that’s why firebug showed all html tags and search information. If there is still any problem, let me know, I will keep and eye on your post!

    • http://www.codersmount.com/ Husamaldin Tayeh

      Perfect Andres, I will update the post soon. I knew it was something to do with the view. Thanks a lot

  • Alif Akbar Fitrawan

    i have try
    but it’s not work

    maybe i’m wrong, where i must locate this code ?

    “$(function(){
    $(“#birds”).autocomplete({
    source: “birds/get_birds” // path to the get_birds method
    });
    });”

    and main.js ??
    i must create main.js ?

    do you have this sourecode ? would you mind if you send me a sourcecode ?

    • http://www.codersmount.com/ Husamaldin Tayeh

      Hi Alif,

      You have two options either you just create a .js file (give it any name you like) with the jQuery code and link to it as you link to any JavaScript file or you can include this code between a in the head section of your HTML main page.

      So if you want to use the code directly in your HTML page, it should look like this (make sure it’s inside the HEAD section):

      $(function(){
      $(“#birds”).autocomplete({
      source: “birds/get_birds” // path to the get_birds method
      });
      });

  • Christian Ticobay

    this tutorial is working, just modify this line (source: “birds/get_birds”) to this ( source:”<php echo site_url(‘birds/get_birds’);?>” )

  • Adityo

    not work for me. need help :
    ==================================
    controller : pages.php
    public function view($page = ‘home’)
    {

    if ( ! file_exists(‘application/views/pages/’.$page.’.php’))
    {
    // Whoops, we don’t have a page for that!
    show_404();
    }

    $this->load->helper(‘url’);

    $data[‘title’] = ucfirst($page); // Capitalize the first letter

    $this->load->view(‘templates/header’, $data);
    $this->load->view(‘pages/’.$page, $data);
    $this->load->view(‘templates/footer’, $data);

    }

    function get_hp(){
    if (isset($_REQUEST[‘term’]))
    {
    $this->load->model(‘ptsqueue_model’);
    $q = strtolower($_REQUEST[‘term’]);
    $this->ptsqueue_model->get_hp($q);
    }
    }
    =====================================
    models :
    public function get_hp($q)
    {
    $this->db->select(‘Usn’);
    $this->db->like(‘Usn’, $q);
    $query = $this->db->get(‘sys_users’);
    if($query->num_rows > 0)
    {
    foreach ($query->result_array() as $row)
    {
    $row_set[] = htmlentities(stripslashes($row[‘Usn’])); //build an array
    }
    echo json_encode($row_set); //format the array into json data
    }
    }
    ==================================
    autocomplete script :
    $(function(){
    $(“#input_hp”).autocomplete({
    source: “pages/get_hp”,
    minLength:1
    });
    });

  • Adityo

    not work for me :(
    need help

    model:

    public function get_hp($q)
    {
    $this->db->select(‘Usn’);
    $this->db->like(‘Usn’, $q);
    $query = $this->db->get(‘sys_users’);
    if($query->num_rows > 0)
    {
    foreach ($query->result_array() as $row)
    {
    $row_set[] = htmlentities(stripslashes($row[‘data’]));
    }
    echo json_encode($row_set); //format the array into json data
    }
    }

    ===============================

    retreive.js :

    $(function(){
    $(“#input_hp”).autocomplete({
    source: “pages/get_hp”, minLength:1
    });
    });

    ===============================

    controller :

    public function view($page = ‘home’)
    {

    if ( ! file_exists(‘application/views/pages/’.$page.’.php’))
    {
    // Whoops, we don’t have a page for that!
    show_404();
    }

    $this->load->helper(‘url’);

    $data[‘title’] = ucfirst($page); // Capitalize the first letter

    $this->load->view(‘templates/header’, $data);
    $this->load->view(‘pages/’.$page, $data);
    $this->load->view(‘templates/footer’, $data);

    }

    function get_hp(){
    if (isset($_GET[‘term’]))
    {
    $this->load->model(‘ptsqueue_model’);
    $q = strtolower($_GET[‘term’]);
    $this->ptsqueue_model->get_hp(‘admin’);

    }
    }

    • http://www.codersmount.com/ Husamaldin Tayeh

      Hi Adityo,
      Ok, let’s try to fix this. First, what is the problem? What kind of data do you get? or what error message?

    • Adityo

      thank you very much

      no error message at all
      simply don’t work

      when I insert some char to textboxt, nothing happen

    • http://www.codersmount.com/ Husamaldin Tayeh

      can you send me the html of your textbox please?

    • Adityo

      home.php :

      ==============================

      home load by view method at controller

    • http://www.codersmount.com/ Husamaldin Tayeh

      Can you check the request with firebug? type some letters in the textbox and check to see if the request was successful using the firebug console.

    • Adityo

      How ??? from DOM panel(firebug) ???

    • http://www.codersmount.com/ Husamaldin Tayeh

      Click the Console panel, not the DOM. Start typing letters and see if the request was successful or an error message is generated.

    • Adityo

      success :)

      thank you very much
      you’re my savior

    • http://www.codersmount.com/ Husamaldin Tayeh

      You are welcome :)

  • Azam Alvi

    What should i do if i want to also display image with text like facebook?

  • richard

    Great post but doesn’t work for me. Auto-complete is working fine and firebug reports OK but no data is being populated. What I’m trying to do is populate a form field & i guess this post doesn’t take account of forms. IN the cut down version of my controller would i have to add the controller in this post into it somewhere. ie just above the if statement and if so what part of the controller. I have tried this with limited success but only seem to get the response filling the page and not populating the input field.

    function driver_addjob()
    {
    // Loads the Add New Job Form for the Website
    $this->load->helper(‘form’);
    $this->load->library(array(‘form_validation’, ‘session’));
    $this->load->model(‘driver_model’);
    $this ->form_validation->set_error_delimiters(”, ”);
    // Validate the form fields
    $this->form_validation->set_rules(‘town’, ‘Nearest Town or City’, ‘trim|required|xss_clean’);
    // Populates “town” auto-complete from the database ???

    if ($this->form_validation->run() == FALSE)

    {
    $this->load->view(‘drivers/driver_addjob.php’);
    }
    else
    {
    $townid = $this->input->post(‘town’);
    $work_jobtitle = $this->input->post(‘jobtitle’);
    $this->driver_model->driver_add_job($makeid, $modelid, $regid, $registration_full, $serviceid, $subserviceid, $work_description, $location_post_code, $townid, $work_jobtitle);
    $this->session->set_flashdata(‘message’, ‘your work request has been added to the system’);
    $this->load->view(‘drivers/driver_addjob_success’);
    }

    }

  • pravalika

    thank you so much….it helped us a lot….

  • rafa

    Gracias!!! me funcionó a la perfección..

  • Fares

    Is it possible to throw away the Employment Application?

  • Jamie

    I was having an issue of the javascript call returning a 500 error (seen in firebug).

    Adding the base_url to the call fixed it. I changed the javascript to:

    $(function(){

    $(“#birds”).autocomplete({

    source: “birds/get_birds” // path to the get_birds method

    });

    });

    • Gurnam Singh

      Check your query in the model

  • anoop

    wow, got it after 2 to 3 iteratio , i got it right, but in this ajax autocomplete call i have to add

    source: “index.php/birds/get_birds” // path to the get_birds method
    to get the call right :) thanks

  • Talha Khan

    Great Post! by the way is there any way i can show the value of the selected label from autocomplete in another text box?

    • http://www.codersmount.com/ Husamaldin Tayeh

      Hi Talha,
      Yes there is a way. Referring to the example used in this tutorial, let’s say we want to display the bird’s name in a text box and the aka value in another. You need to create another textbox and give it an ID of “birds_aka”. Use the following JavaScript:

      $(document).ready(function() {
      $(“#birds”).autocomplete({
      minLength: 0,
      source: “birds/get_birds”,
      focus: function( event, ui ) {
      $( “#birds” ).val( ui.item.label );
      return false;
      },
      select: function( event, ui ) {
      $(“#birds_aka”).val(ui.item.aka);
      return false;
      }
      })
      });

    • Talha Khan

      That Worked! :) Thanks Man!

  • Haveno

    Very good! More tuts please =)

  • Ryan Borja

    Hello. Just want to say thank you for this tutorial

    • http://www.codersmount.com/ Husamaldin Tayeh

      You are welcome :)

  • Joan

    Hi,

    Great tut, working like a charm thanks.

    Three suggestions though.

    1. The way you usually expect and autocomplete to work is by guessing only the subsequent characters. To reflect that, I recommend using $this->db->like(‘bird’, $q, ‘after’); in the model, which will only add one wildcard in the end.

    2. htmlentities() in the model will mess your accented letters (é,ö,ü, etc), even if you work with utf-8 all the way. I simply took it away and chose to trust my database

    3. ui-autocomplete-loading { } in the css did not cut it because of hierarchy. I had to be more specific and write input.ui-autocomplete-loading { }

    Otherwise it was a very very good walkthrough, thank you for that.

    Best,
    Joan

    • http://www.codersmount.com/ Husamaldin Tayeh

      Hi Joan,

      I am glad that you liked he tutorial. Thank you for the points you pointed out. I will sure try them out and probably add them to the tutorial. Thanks again.

  • Omar Salim

    Great Tutorial, really sorted out my headache, according to chrome and firebug console, a response is received, but It does not appear.

  • Roman

    Hi Husamaldin. I get {“error”:”100515″} . Where I am wrong? Thanks.

    Roman.

  • Jeswin George

    Thanks…

  • Omkar Hendre

    Thanx friend it works for me with little modifications

  • omkar hendre

    plz help me

  • omkar hendre

    i got error that auto complete is not a function

  • Julien

    Hello ! Im tryin to use your code but something is wrong. Husamaldin can you give me some help ?

    First of all my working view nouvelle.php is :

    My controller sorties.php contains :

    function get_birds(){

    $this->load->model(‘birds_model’);

    if (isset($_GET[‘term’])){

    $q = strtolower($_GET[‘term’]);

    $this->birds_model->get_bird($q);

    }

    }

    My birds_model contains :

    db->select(‘bird’);

    $this->db->like(‘bird’, $q);

    $query = $this->db->get(‘birds’);

    if($query->num_rows() > 0){

    foreach ($query->result_array() as $row){

    $row_set[] = htmlentities(stripslashes($row[‘bird’])); //build an array

    }

    echo json_encode($row_set); //format the array into json data

    }

    }

    }

    My default.php layout (working) contains :

    $(function(){

    $(“#birds”).autocomplete({

    source: “sorties/get_birds” // path to the get_birds method

    });

    });

    Results files appaers but autocomplete doesnt work. Can you help me ?

  • Ahmad Wahyu Rosyadi

    Thanks :)

  • Niaz Prodhan

    Great post. Thanks. May be i’ve missed it. But can you please let me know from where the get method data saved in ‘term’ is written in the view ? I am not getting from where you are declaring ‘term’ variable. Thanks in advance

    • http://www.codersmount.com/ Husamaldin Tayeh

      The ‘term’ variable is defined by the jQuery UI Autocomplete.

    • Niaz Prodhan

      I am receiving data in below format. But autocomplete panel is not appearing for some reasons. Can you please help ?

      array(3) {
      [0]=>
      object(stdClass)#15 (2) {
      [“label”]=>
      string(20) “Dr. Rahim Sardar Mir”
      [“value”]=>
      string(15) “Surgeon, Birdem”
      }
      [1]=>
      object(stdClass)#16 (2) {
      [“label”]=>
      string(16) “Dr. Rahim sardar”
      [“value”]=>
      string(14) “President, BMA”
      }
      [2]=>
      object(stdClass)#17 (2) {
      [“label”]=>
      string(16) “Dr. Rahim sardar”
      [“value”]=>
      string(14) “President, BMA”
      }
      }

  • Akash KV

    thanks bro….

  • Amit Srivastava

    Hey Husamaldin Tayeh,

    Great man. i love it.

    From last few days m working on Tag management using CodeIgniter.

    I have done it. but there is some issue on tag management data are not coming from database.

    i wanted to fetch the values from DB. using mysql. i have attached a print screen of my module.

    If u could help on it. so pls i’ll very thankful to you Tayeh.

    1- I wanted to fetch the multiple values from database with cross X button to remove it. Like “WordPress Tag”

    in a textarea not in textbox. I think if u will see attached image . u could understand what i wanted to be..??

    “M hungry to do this but knw buddy is here to help me … Pls do something ”

    “Autocompete multiple values in textarea using CoeIgniter +JQuery+AJAX+Database”

    Sorry for bad english.

    Thanks in Advance .. Tayeh.

    • Amit Srivastava

      Hey Husamaldin Tayeh,

      Great man. i love it.

      From last few days m working on Tag management using CodeIgniter.

      I have done it. but there is some issue on tag management data are not coming from database.

      i wanted to fetch the values from DB. using mysql. i have attached a print screen of my module.

      If u could help on it. so pls i’ll very thankful to you Tayeh.

      1- I wanted to fetch the multiple values from database with cross X button to remove it. Like “WordPress Tag”

      in a textarea not in textbox. I think if u will see attached image . u could understand what i wanted to be..??

      “M hungry to do this but knw buddy is here to help me … Pls do something ”

      “Autocompete multiple values in textarea using CoeIgniter +JQuery+AJAX+Database”

      Sorry for bad english.

      Thanks in Advance .. Tayeh.

      10-10-14

  • Christian David Will

    Hi, thank you very much for this code, it helped me a lot. I just have one question, if I want to return to another field other value, for instance “aka” how can I do that?

  • freddy

    Thanks alot

    my 1st question is where came from input type name=”term”, only input type with id=”bird” , so what is term ?

    if (isset($_GET[‘term’])){
    $q = strtolower($_GET[‘term’]);
    $this->birds_model->get_bird($q);

    the 2nd question is we put these code in view right ?

    $(function(){
    $(“#birds”).autocomplete({
    source: “birds/get_birds” // path to the get_birds method
    });
    });

    so is it true when i change to be

    $(function(){
    $(“#birds”).autocomplete({
    source: “birds/get_birds” // path to the get_birds method
    });
    });

    Thanks for fasr respon mr

    • Paula

      Hi, from what I understand, ‘term’ is what you type in the input field – it’s already defined in the jquery code and its what is matched to the values in the database. :)

  • freddy

    any one can give me link to downloa it, i’m new bie and really need it, i have been trying this tutorial but still doesnt work ?

    sidaurukfreddy@gmail.com

  • http://www.aolakh.com Ahmad Faraz Aolakh

    Thanks a lot.
    Really helpful tutorial..

    Thanks again.

  • Varun Neb

    Thank a lot buddy it helps me alot !!!! :)

  • Mayank

    auto complete not working for me

    auto.php (view)

    Demo Auto Complete
    <link href="assets/css/jquery-ui.css” type=”text/css” rel=”stylesheet”>
    <script type="text/javascript" src="assets/js/jquery.js”>
    <script type="text/javascript" src="assets/js/jquery-ui.js”>

    $(document).ready(function(){
    $(‘#pro’).autocomplete({
    source:””
    });
    });

    ——————————————–

    auto.php (model)
    db->select(‘user_name’);
    $this->db->like(‘user_name’, $q);
    $query = $this->db->get(‘user’);
    if($query->num_rows > 0){
    foreach ($query->result_array() as $row){
    $row_set[] = htmlentities(stripslashes($row[‘user_name’])); //build an array
    }
    echo json_encode($row_set); //format the array into json data
    }
    }
    }
    ?>

    ————————————————-
    auto.php (controller)
    load->helper(‘url’);
    $this->load->view(‘pages/auto’);
    }

    function get_birds(){
    $this->load->model(‘auto’);
    if (isset($_GET[‘term’])){
    $q = strtolower($_GET[‘term’]);
    $this->birds_model->get_bird($q);
    }
    }
    }
    ?>

  • Long

    thanks you so much

  • rahul

    $_GET[‘term’] is not define

    • Paula

      This is defined in the jquery itself from what I know. Basically ‘term’ is whatever you type in the input field.

  • Rasik EC

    where can i download “jquery.ui.autocomplete.css”?. in my css file, i cant find the .ui-autocomplete-loading calass or ui-autocomplete-input calass.

  • tanpa nama

    Hi, i think this useful tutorial for get another value from autocomplete.

    I was tried this tutorial, i follow step by step, but on that autocomplete, i get “true” value not bird. Can you give an advice?

  • Paula

    Hello! Thanks for this tutorial, I terribly needed help on using autocomplete with the MVC framework. :)

    Just a question though, I found that the “term” appends itself to the url when the autocomplete function is called. So what happens is that I get the following URL: “index.php/birds/get_birds?term=example”.

    This is causing a problem – when I check the Chrome console the error is 404 (Not Found) since the URL can’t be found. But when I go to just “index.php/birds/get_birds”, the array is printed on screen, meaning the code works.

    Does anyone know how to solve this? Or if there’s something else I should modify so that “term” isn’t added to the URL?

    Thanks a lot for the help! :)

  • Vlad Dvernik

    got it work! awesome thank you

  • Yanapul Atmadja

    i use this autocomplete in multiple textbox (dynamic add textbox in row table), but the autocomplete only work for the textbox in first row, what do i miss?

  • Gurnam Singh

    This is rocking . Thanks

  • Yi Yu

    Thanks a lot, that’s all i need.

  • shilpa

    hi i need the zip code for this

  • http://ferindra.web.ugm.ac.id/ ferindra

    oh, thanks! great tutorial, and it works even in latest codeigniter release (3.0.1)

    • Idham Muhammad

      what database do you use? i am use codeigniter 3.x.x and it doesn’t work to appear the textbox.

  • Tarun

    This is good, but you forgot to add ——$this->load->database();——- in the model

  • pradeep

    hello sir this my code..but its not working plzz help me..

    controller:

    function get_locations(){

    if (isset($_GET[‘term’])){

    $q = strtolower($_GET[‘term’]);

    $this->Modelrent->get_location_for_autocomplete($q);

    }

    }

    Model:

    function get_location_for_autocomplete($q){

    $this->db->select(‘location_name’);

    $this->db->like(‘location_name’, $q);

    $query = $this->db->get($this->tbl_location);

    if($query->num_rows > 0){

    foreach ($query->result_array() as $row){

    $row_set[] = htmlentities(stripslashes($row[‘location_name’])); //build an array

    }

    // echo json_encode($row_set); //format the array into json data

    }

    }

    view:

    $(document).ready

    // alert (“hi”);

    (function(){

    $(“#location_name”).autocomplete({

    source: ‘Rent_controller/get_locations’

    });

    });

    ihave also used this:

    $(function(){

    $(“#location_name”).autocomplete({

    source: ‘Rent_controller/get_locations’

    });

    });

  • pradeep

    this error comming in console Uncaught TypeError: $(…).autocomplete is not a function

    http://localhost/css/bootstrap.min.css Failed to load resource: the server responded with a status of 404 (Not Found)

  • swan

    can u put the source code.please..mine doesnt work..and am cofused of the link that is passed for jquery and all…can u send the source code

  • gish

    I get 404(Not found) in the console each time i type a letter.. can you please help me to identify where i’m doing wrong?

  • gunavantha

    Hi, Thanks for awesome post, When I try to run this code I am getting output like 0 no results found I am not getting birds list. I am struggling to do this can anyone help me please??

  • Nicko Valentino

    num rows is a function, not a variable, so write it num_rows() instead of num_rows
    or it will not return the query

    • http://www.codersmount.com/ Husamaldin Tayeh

      I have corrected it. Thanks Nicko

  • Rook

    This code work properly but after I click next page and then it won’t work.

  • Ahsan Iqbal

    great work
    plzzz help me .
    autocomplete option not show any sugestion..
    i think problem is in ajax function

    //my view code is

    $(function(){
    $(“#birds”).autocomplete({
    source: “birds/get_birds” // path to the get_birds method
    });
    });

    // controller code is

    load->view(‘birds_view’);
    }

    function get_birds(){
    $this->load->model(‘birds_model’);
    if (isset($_GET[‘term’])){
    $q = strtolower($_GET[‘term’]);
    $this->birds_model->get_bird($q);
    }
    }
    }

    // mode is

    db->select(‘bird’);
    $this->db->like(‘bird’, $q);
    $query = $this->db->get(‘birds’);
    if($query->num_rows() > 0){
    foreach ($query->result_array() as $row){
    $row_set[] = htmlentities(stripslashes($row[‘bird’])); //build an array
    }
    echo json_encode($row_set); //format the array into json data
    }
    }
    }

    anyone plzz help working on this topic for many weeks but find no solution

    • Ahsan Iqbal

      anyone plzzz help me

    • Koha Choji

      I know this is a year ago and you’ve probably moved on but I do notice the probable typos in the link and script tags – “assests” should be “assets”

  • agung

    nice tutorial, thank you…but my image still not appear. how to set source path of image in codeigniter? img src=”image path”

  • newbieonthego

    thanks for this great tutorial but i have a problem with special characters , im getting &NTILDE; instead of ñ

  • Muhammad Ishaq

    Where i will put the jquery code please

  • Muhammad Ishaq

    i am new in codeIgniter please send me correct code for auto complete i need it please

  • Ángel

    “2- Linking to the JavaScript and CSS files”: main index file = view of default controller?

    Thanks!

  • http://geriel.com Geriel Castro

    thanks brother

  • Junior ferreira

    great tutorial, now how do I read these values by putting in another input.

    [{Label: “Great Bittern” value “Botaurus stellaris”}, {label: “Little Grebe” value “Tachybaptus ruficollis”}, …]

    place the label and the value of inputs.

  • raju

    Nice

  • Kumar Ujjwal

    bro….you have saved my life…… you are awesome….keep up the good work

  • dibyajit debnath

    view page shows nothings

  • Siti Mei

    Thank you so much, this is so helpfull

  • Aye Su Naing

    Great tutorial , you saved my days.
    Thank you very much.