Loading data remotely in Select2 – CodeIgniter 3

Select2 is easier to initialize on the HTML <select > element. You can either use static data or load data remotely using ajax option.

Requires to return response in a defined format to load content using AJAX.

In this tutorial, I show how you can load data remotely in a select2 in CodeIgniter 3 project.

Loading data remotely in Select2 – CodeIgniter 3


Contents

  1. Table structure
  2. Database Configuration
  3. Create Model
  4. Create Controller
  5. Create View
  6. Demo
  7. Conclusion

1. Table structure

In this example, I am using users table and added some records –

CREATE TABLE `users` (
  `id` int(11) NOT NULL PRIMARY KEY AUTO_INCREMENT,
  `username` varchar(80) NOT NULL,
  `name` varchar(80) NOT NULL,
  `email` varchar(80) NOT NULL
) ENGINE=InnoDB DEFAULT CHARSET=utf8;

2. Database Configuration

Navigate to application/config/database.php and define the Database connection.

$db['default'] = array(
 'dsn' => '',
 'hostname' => 'localhost',
 'username' => 'root', // Username
 'password' => '', // Password
 'database' => 'tutorial', // Database name
 'dbdriver' => 'mysqli',
 'dbprefix' => '',
 'pconnect' => FALSE,
 'db_debug' => (ENVIRONMENT !== 'production'),
 'cache_on' => FALSE,
 'cachedir' => '',
 'char_set' => 'utf8',
 'dbcollat' => 'utf8_general_ci',
 'swap_pre' => '',
 'encrypt' => FALSE,
 'compress' => FALSE,
 'stricton' => FALSE,
 'failover' => array(),
 'save_queries' => TRUE
);

Default controller

Open application/config/routes.php and edit default_controller value to User.

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

Load Database

To access the MySQL database require loading database library.

Open application/config/autoload.php and add the database in libraries array().

$autoload['libraries'] = array("database");

3. Create Model

Create a Main_model.php file in application/models/ folder.

Create a single method –

  • getUsers – This method takes a single parameter.

Fetch all records from the users table and use $searchTerm in where clause for searching in the name field.

Loop on the fetched records and initialize $data Array with id and text keys.

Return $data.

Completed Code

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

class Main_model extends CI_Model {

   // Fetch users
   function getUsers($searchTerm=""){

      // Fetch users
      $this->db->select('*');
      $this->db->where("name like '%".$searchTerm."%' ");
      $fetched_records = $this->db->get('users');
      $users = $fetched_records->result_array();

      // Initialize Array with fetched data
      $data = array();
      foreach($users as $user){
          $data[] = array("id"=>$user['id'], "text"=>$user['name']);
      }
      return $data;
   }

}

4. Create Controller

Create a User.php file in application/controllers/ folder.

Create 3 methods –

  • __construct – Load url helper and Main_model model.
  • index – Load user_view view.
  • getUsers – This method is used to handle the AJAX request.

Get the POST searchTerm and assign in $searchTerm.

Pass the $searchTerm in getUsers() method of Main_model to get users records Array.

Return $response in Array format.

Completed Code

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

class User extends CI_Controller {

   public function __construct(){

      parent::__construct();

      // load base_url
      $this->load->helper('url');

      // Load Model
      $this->load->model('Main_model');
   }

   public function index() {
      $this->load->view('user_view');
   }

   // Get users
   public function getUsers(){

      // Search term
      $searchTerm = $this->input->post('searchTerm');

      // Get users
      $response = $this->Main_model->getUsers($searchTerm);

      echo json_encode($response);
   }
}

5. Create View

Create a new folder assets at the project root.

Download select2 plugin from here at extract it in assets folder and also copy jQuery library.

Create a user_view.php file in application/views/ folder.

Include select2 CSS, select2 JS and jQuery library in the <head> section.

Create a <select id='selUser' > element.


Script

Initialize select2 on the <select > element and add ajax option.

Set url to User controller getUsers method – '<?= base_url() ?>index.php/User/getUsers’, type: “post”, dataType: ‘json’.

With data pass the typed value as data.

Handle AJAX response with processResults. Initialize results with the response.

Completed Code

<?php
defined('BASEPATH') OR exit('No direct script access allowed');
?><!DOCTYPE html>
<html lang="en">
<head>
   <meta charset="utf-8">
   <title>Loading data remotely in Select2 – CodeIgniter 3</title>

   <!-- Select2 CSS -->
   <link href="<?= base_url() ?>assets/select2/dist/css/select2.min.css" rel="stylesheet" />

   <!-- jQuery library -->
   <script src="<?= base_url() ?>assets/jquery-3.3.1.min.js"></script>

   <!-- Select2 JS -->
   <script src="<?= base_url() ?>assets/select2/dist/js/select2.min.js"></script>
   
   
   <!-- CDN -->
   <!--  <link href="https://cdnjs.cloudflare.com/ajax/libs/select2/4.0.6-rc.0/css/select2.min.css" rel="stylesheet" />

   <script src="https://ajax.googleapis.com/ajax/libs/jquery/3.4.0/jquery.min.js"></script>

   <script src="https://cdnjs.cloudflare.com/ajax/libs/select2/4.0.6-rc.0/js/select2.min.js"></script>
   -->
</head>
<body>

   <!-- Select Element -->
   <select id='selUser' style='width: 200px;'>
      <option value='0'>-- Select user --</option>
   </select>

   <!-- Script -->
   <script type="text/javascript">
   $(document).ready(function(){

      $("#selUser").select2({
         ajax: { 
           url: '<?= base_url() ?>index.php/User/getUsers',
           type: "post",
           dataType: 'json',
           delay: 250,
           data: function (params) {
              return {
                searchTerm: params.term // search term
              };
           },
           processResults: function (response) {
              return {
                 results: response
              };
           },
           cache: true
         }
     });
   });
   </script>
</body>
</html>

6. Demo

View Demo


7. Conclusion

Return response must have id and text key otherwise data would not show properly on the page.

You can also view this tutorial to know how you can add select2 and load data in the CodeIgniter 4 project.

If you found this tutorial helpful then don't forget to share.

9 thoughts on “Loading data remotely in Select2 – CodeIgniter 3”

  1. i tried this code, but select2 won’t show the list data and won’t show the result of search but on console i see the array. how to fix that ? thanks before

    Reply
  2. Hello,

    I use your tutorial to get value from dropdown on select.

    I create
    function submitForm(){
    document.getElementById(‘forma_id’).submit();
    }
    and now need to post some variables after select.
    Also, need to get option value selected

    Reply

Leave a Comment