Loading data remotely in Select2 – CodeIgniter

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.

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

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

2. 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. Model

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

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. Controller

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

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

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. View

Create a new directory assets at the project root.

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

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

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

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


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

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</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> -->
<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>

6. Conclusion

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

Related Posts