codeigniter ajax dropdown example

Today, We want to share with you codeigniter ajax dropdown example.In this post we will show you how to get value in dropdownlist from database in codeigniter, hear for Codeigniter Ajax dropdown we will give you demo and example for implement.In this post, we will learn about Country State City Dynamic Dependent Dropdown Using Jquery In Codeigniter with an example.

Codeigniter – Dynamic dependent dropdown using jquery ajax Example

Step 1: Download Fresh Codeigniter 3

download fresh version of Codeigniter 3
download from here Free Download Codeigniter 3

Step 2: Create Database and Configuration

list_state table:

CREATE TABLE `list_state` (
  `id` int(11) NOT NULL,
  `name` varchar(155) NOT NULL,
  `created_at` timestamp NOT NULL DEFAULT CURRENT_TIMESTAMP ON UPDATE CURRENT_TIMESTAMP,
  `updated_at` timestamp NOT NULL DEFAULT '0000-00-00 00:00:00'
) ENGINE=InnoDB DEFAULT CHARSET=latin1;

list_cities table:

CREATE TABLE `list_cities` (
  `id` int(11) NOT NULL,
  `state_id` int(12) NOT NULL,
  `name` varchar(155) NOT NULL,
  `created_at` timestamp NOT NULL DEFAULT CURRENT_TIMESTAMP ON UPDATE CURRENT_TIMESTAMP,
  `updated_at` timestamp NOT NULL DEFAULT '0000-00-00 00:00:00'
) ENGINE=InnoDB DEFAULT CHARSET=latin1;

application/config/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' => 'Radhe_krishna',
	'password' => '[email protected]#$#%$54',
	'database' => 'pakainfo',
	'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
);

Step 3: Add Route

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['commentfrm'] = 'HomeController';
$route['commentfrm/ajax/(:any)'] = 'HomeController/commentfrmAjax/$1';

Step 4: Create Controller

application/controllers/HomeController.php

<?php


class HomeController extends CI_Controller {


   /**
    * Manage __construct
    *
    * @return Response
   */
   public function __construct() { 
      parent::__construct();
      $this->load->database();
   }


   /**
    * Manage index
    *
    * @return Response
   */
   public function index() {
      $states = $this->db->get("list_state")->result();
      $this->load->view('commentfrm', array('states' => $states )); 
   } 


   /**
    * Manage storeProfileDP
    *
    * @return Response
   */
   public function commentfrmAjax($id) { 
       $result = $this->db->where("state_id",$id)->get("list_cities")->result();
       echo json_encode($result);
   }


} 


?>

Step 5: Create View Files

application/views/commentfrm.php

<!DOCTYPE html>
<html>
<head>
    <title>Codeigniter Dependent Dropdown Example with demo</title>
    <script src="jquery.js"></script>
    <link rel="stylesheet" href="bootstrap-3.min.css">
</head>


<body>
<div class="container">
    <div class="panel panel-default">
      <div class="panel-heading">Select State and get bellow Related City</div>
      <div class="panel-body">


            <div class="form-group">
                <label for="title">Select State:</label>
                <select name="state" class="form-control" style="width:350px">
                    <option value="">--- Select State ---</option>
                    <?php
                        foreach ($states as $key => $value) {
                            echo "<option value='".$value->id."'>".$value->name."</option>";
                        }
                    ?>
                </select>
            </div>


            <div class="form-group">
                <label for="title">Select City:</label>
                <select name="city" class="form-control" style="width:350px">
                </select>
            </div>


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


<script type="text/javascript">


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


</body>
</html>

I hope you get an idea about Dynamic dependent dropdown in CodeIgniter with AJAX.
I would like to have feedback on my infinityknow.com blog.
Your valuable feedback, question, or comments about this article are always welcome.
If you enjoyed and liked this post, don’t forget to share.