Codeigniter 3 – Dynamic dependent dropdown using jquery ajax with example

Codeigniter 3 – Dynamic dependent dropdown using jquery ajax with example

In this post we will give you information about Codeigniter 3 – Dynamic dependent dropdown using jquery ajax with example. Hear we will give you detail about Codeigniter 3 – Dynamic dependent dropdown using jquery ajax with exampleAnd how to use it also give you demo for it if it is necessary.

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:

CREATETABLE'countries' (
 'id'int(11) NOTNULLAUTO_INCREMENT,
 'name'varchar(100) NOTNULL,
 'created_at'timestampNOTNULLDEFAULTCURRENT_TIMESTAMP,
 'updated_at'datetimeDEFAULTNULL,
 PRIMARYKEY ('id')
) ENGINE=InnoDB AUTO_INCREMENT=3DEFAULTCHARSET=latin1


states table:

CREATETABLE'states' (
 'id'int(11) NOTNULLAUTO_INCREMENT,
 'country_id'int(11) NOTNULL,
 'name'varchar(100) NOTNULL,
 'created_at'timestampNOTNULLDEFAULTCURRENT_TIMESTAMP,
 'updated_at'datetimeDEFAULTNULL,
 PRIMARYKEY ('id')
) ENGINE=InnoDB AUTO_INCREMENT=3DEFAULTCHARSET=latin1


database.php

<?php
defined('BASEPATH') ORexit('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') ORexit('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

classDropdownsextends CI_Controller {

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

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

   publicfunctiongetStateList($id) { 
       $states=$this->db->where("country_id",$id)->get("states")->result();
       echojson_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>
    <linkrel="stylesheet"href="http://www.onlinecode.org/css/bootstrap.css">    
    <script src="/https://onlinecode.org/js/jquery.js"></script>
</head>

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

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

            <divclass="form-group">
                <labelfor="title">Select State:</label>
                <selectname="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>

Try this..

Hope this code and post will helped you for implement Codeigniter 3 – Dynamic dependent dropdown using jquery ajax with example. if you need any help or any feedback give it in comment section or you have good idea about this post you can give it comment section. Your comment will help us for help you more and improve us. we will give you this type of more interesting post in featured also so, For more interesting post and code Keep reading our blogs

For More Info See :: laravel And github

Leave a Comment

Your email address will not be published. Required fields are marked *

  +  8  =  12

We're accepting well-written guest posts and this is a great opportunity to collaborate : Contact US