How to use select2 ajax autocomplete from database in Codeigniter 3 ?

Today now in this post, I am going to show you how we can make select2 dynamic autocomplete from the database table in our Codeigniter application. Now in this post we can lean about how to implement the ajax autocomplete in our Codeigniter 3 application.

We are know that Select2 is a Jquery plugin and it is very famous jquery plugin. By using select2 plugin we can do the several thing as like select box with the search, select option also with the check box, ajax auto-complete etc.

Sometimes we may need to do the autocomplete task with the select box when we have a large amount of data as like as products, items, category, tags, users etc. Now on that time we can’t load all the data at the same time and it’s hard to find that item from the several records. So we can use select2.js plugin to provides us with the select box also with the search. And also Ajax dynamically auto complete on that way page will never be load more and it will work fine also.

Now we can make this simple by using following few step as listed bellow.

Step 1: Make View File

In first step, we need to create the view file, If you are installed a fresh codeigniter then you can find all file welcome_message.php on views folder and need to put bellow code on that file.

application/views/welcome_message.php

<html lang="en">
<head>


  <title>Jquery select2 ajax autocomplete example code with demo</title>
  <script src="http://ajax.googleapis.com/ajax/libs/jquery/1.9.1/jquery.js"></script>
  <link href="https://cdnjs.cloudflare.com/ajax/libs/select2/4.0.3/css/select2.min.css" rel="stylesheet" />
  <script src="https://cdnjs.cloudflare.com/ajax/libs/select2/4.0.3/js/select2.min.js"></script>


</head>
<body>


<div style="width:420px;margin:0px auto;margin-top:30px;height:500px;">
  <h2>Select Box with Search Option Jquery Select2.js</h2>
  <select class="itemName form-control" style="width:500px" name="itemName"></select>
</div>


<script type="text/javascript">


      $('.itemName').select2({
        placeholder: '--- Select Item ---',
        ajax: {
          url: '/search',
          dataType: 'json',
          delay: 250,
          processResults: function (data) {
            return {
              results: data
            };
          },
          cache: true
        }
      });


</script>


</body>
</html>
Step 2: Create Route

Now in this step we have to add one route for the ajax search data. So open the routes.php file and add the code like as bellow:

application/config/routes.php

$route['default_controller'] = 'welcome';
$route['404_override'] = '';
$route['translate_uri_dashes'] = FALSE;
$route['search'] = "search/index";
Step 3: Create Controller

So in the last step we need to create the Search Controller, in this file we will write the search database logic.

Now need to create new Search.php file in controllers folder and put the bellow code:

application/controllers/Search.php

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


class Search extends CI_Controller {


	/**
	 * Index Page for this controller.
	 *
	 * Maps to the following URL
	 * 		http://example.com/index.php/welcome
	 *	- or -
	 * 		http://example.com/index.php/welcome/index
	 *	- or -
	 * Since this controller is set as the default controller in
	 * config/routes.php, it's displayed at http://example.com/
	 *
	 * So any other public methods not prefixed with an underscore will
	 * map to /index.php/welcome/

	 * @see https://codeigniter.com/user_guide/general/urls.html
	 */
	public function index()
	{
		$json = [];


		$this->load->database();

		
		if(!empty($this->input->get("q"))){
			$this->db->like('name', $this->input->get("q"));
			$query = $this->db->select('id,name as text')
						->limit(10)
						->get("tags");
			$json = $query->result();
		}

		
		echo json_encode($json);
	}
}

Read Also: How to implement infinite ajax scroll pagination in Laravel?

Thanks for read. I hope it help you. For more you can follow us on facebook

Shahriar Sagor

My name is Shahriar sagor. I'm a developer. I live in Bangladesh and I love to write tutorials and tips that will help to other Developer's. I am a big fan of PHP, Javascript, JQuery, Laravel, Codeigniter, VueJS, AngularJS and Bootstrap from the early stage.