Codeigniter 3 - Dynamic dependent dropdown using jquery ajax with example

Codeigniter 3 - Dynamic dependent dropdown using jquery ajax with example

In this tutorial, I am going to tell you how to populate dynamic dependent dropdown using jQuery Ajax in our Codeigniter application.

Dynamic dependent dropdown select box is mostly used in country,state and city selection in web application.

It's very easy to load dynamic data in select dropdown without page refresh using jQuery Ajax.

In this example, I will display the all countries and when a country is selected then the respective states will be listed in another dropdown.

For this example, I will create two tables "countries" and "states" in database.

To start with this example, First download the fresh version of Codeigniter and configure it in your system.

Step1: Configure database

In this step, I will create a demo database and create two tables inside the demo database.

countries table:
CREATE TABLE `countries` (
 `id` int(11) NOT NULL AUTO_INCREMENT,
 `name` varchar(100) NOT NULL,
 `created_at` timestamp NOT NULL DEFAULT CURRENT_TIMESTAMP,
 `updated_at` datetime DEFAULT NULL,
 PRIMARY KEY (`id`)
) ENGINE=InnoDB AUTO_INCREMENT=3 DEFAULT CHARSET=latin1
states table:
CREATE TABLE `states` (
 `id` int(11) NOT NULL AUTO_INCREMENT,
 `country_id` int(11) NOT NULL,
 `name` varchar(100) NOT NULL,
 `created_at` timestamp NOT NULL DEFAULT CURRENT_TIMESTAMP,
 `updated_at` datetime DEFAULT NULL,
 PRIMARY KEY (`id`)
) ENGINE=InnoDB AUTO_INCREMENT=3 DEFAULT CHARSET=latin1
database.php
<?php
defined('BASEPATH') OR exit('No direct script access allowed');


$active_group = 'default';
$query_builder = TRUE;


$db['default'] = array(
  'dsn'  => '',
  'hostname' => 'localhost',
  'username' => 'root',
  'password' => 'xxxx',
  'database' => 'demo',
  '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
);
Step2: Add Routes

In this step, I will add two routes to handle the request.

application/config/routes.php
<?php
defined('BASEPATH') OR exit('No direct script access allowed');

$route['default_controller'] = 'welcome';
$route['404_override'] = '';
$route['translate_uri_dashes'] = FALSE;
$route['dependent-dropdown'] = 'Dropdowns';
$route['dependent-dropdown/ajax/(:any)'] = 'Dropdowns/getStateList/$1';
Step3: Create Controller

In this step, I will create a controller "Dropdowns.php" in following path application/controllers/.

In this controllers, I have 3 functions : _construct(), index(), getStateList().

  • _construct() - Manually connect with database.
  • index() - Get the country data from database and pass it to the view.
  • getStateList() - Based on the country id, get the state data from database and return the data in JSON format.
application/controllers/Dropdowns.php
<?php

class Dropdowns extends CI_Controller {

   public function __construct() { 
      parent::__construct();
      $this->load->database();
   }

   public function index() {
      $countries = $this->db->get("countries")->result();
      $this->load->view('dependent_dropdown', array('countries' => $countries )); 
   } 

   public function getStateList($id) { 
       $states = $this->db->where("country_id",$id)->get("states")->result();
       echo json_encode($states);
   }


} 


?>
Step4: Create View File

In this step, I will create a view file "dependent_dropdown.php" in following path .

application/views/dependent_dropdown.php
<!DOCTYPE html>
<html>
<head>
    <title>Codeigniter Dependent Dropdown Example with demo</title>
    <link rel="stylesheet" href="http://www.expertphp.in/css/bootstrap.css">    
    <script src="http://demo.expertphp.in/js/jquery.js"></script>
</head>

<body>
<div class="container">
    <div class="panel panel-default">
      <div class="panel-heading">Populate dropdown using ajax in codeigniter</div>
      <div class="panel-body">

            <div class="form-group">
                <label for="title">Select Country:</label>
                <select name="country" class="form-control">
                    <option value="">Select Country</option>
                    <?php
                        if(!empty($countries)){
                            foreach ($countries as $key => $value) {
                                echo "<option value='".$value->id."'>".$value->name."</option>";
                            }
                        }else{
                            echo '<option value="">Country not available</option>';
                        }
                    ?>
                </select>
            </div>

            <div class="form-group">
                <label for="title">Select State:</label>
                <select name="state" class="form-control">
                </select>
            </div>


      </div>
    </div>
</div>

<script type="text/javascript">

    $(document).ready(function() {
        $('select[name="country"]').on('change', function() {
            var countryId = $(this).val();
            if(countryId) {
                $.ajax({
                    url: 'dependent-dropdown/ajax/'+countryId,
                    type: "GET",
                    dataType: "json",
                    success:function(data) {
                        $('select[name="state"]').empty();
                        $.each(data, function(key, value) {
                            $('select[name="state"]').append('<option value="'+ value.id +'">'+ value.name +'</option>');
                        });
                    }
                });
            }else{
                $('select[name="state"]').empty();
            }
        });
    });
</script>


</body>
</html>

Phone: (+91) 8800417876
Noida, 201301
sakarya escort akyazı escort arifiye escort erenler escort eve gelen escort ferizli escort geyve escort hendek escort otele gelen escort sapanca escort söğütlü escort taraklı escort
sakarya escort - akyazı escort - arifiye escort - erenler escort - eve gelen escort - ferizli escort - geyve escort - hendek escort - karapürçek escort - karasu escort - kaynarca escort - kocaali escort - otele gelen escort - pamukova escort - sapanca escort - söğütlü escort - taraklı escort
sapanca escort hendek escort karasu escort escort sakarya sakarya escort bayan adapazarı escort sakarya escort sakarya escort sakarya escort sakarya escort sakarya escort sakarya escort