Codeigniter - Dynamic dependent dropdown using jquery ajax Example

By Hardik Savani | May 25, 2017 | | 23733 Viewer | Category : PHP Javascript Bootstrap jQuery Codeigniter Ajax


In this post, we will learn how to populate dynamic dependent drop down select box using jquery ajax in our codeigniter application.

We may sometimes require to make dependent dropdown from database like when state select at that time bellow city drop down list should change, i mean related to selected state. In this example i have two tables and there are listed bellow:

1.demo_state

2.demo_cities

So, when user will change state at that time, dynamically change city drop down box from database. you can implement this example in your application by follow bellow few step. you have to just follow few step:

Step 1: Download Fresh Codeigniter 3

In First step we will download fresh version of Codeigniter 3, so if you haven't download yet then download from here : Download Codeigniter 3.

Step 2: Create Database and Configuration

In this step we will create new database "test" and add two new table "demo_state" and "demo_cities" in test database. You can use following SQL Query for create "demo_cities" and "demo_state" table. So let's create using bellow sql query:

demo_state table:

CREATE TABLE `demo_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;

demo_cities table:

CREATE TABLE `demo_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;

After create database and table successfully, we have to configuration of database in our Codeigniter 3 application, so open database.php file and add your database name, username and password.

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' => 'root',

'password' => 'root',

'database' => 'test',

'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

In this step you have to add two new routes in our route file. We will manage layout and another route for ajax, so let's put route as bellow code:

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['myform'] = 'HomeController';

$route['myform/ajax/(:any)'] = 'HomeController/myformAjax/$1';

Step 4: Create Controller

Ok, now first we have to create one new controller HomeController with index method. so create HomeController.php file in this path application/controllers/HomeController.php and put bellow code in this file:

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("demo_state")->result();

$this->load->view('myform', array('states' => $states ));

}


/**

* Manage uploadImage

*

* @return Response

*/

public function myformAjax($id) {

$result = $this->db->where("state_id",$id)->get("demo_cities")->result();

echo json_encode($result);

}


}


?>

Step 5: Create View Files

In this step, we will create myform.php view and here we will create form with two dropdown select box. We also write ajax code here:

application/views/myform.php

<!DOCTYPE html>

<html>

<head>

<title>Codeigniter Dependent Dropdown Example with demo</title>

<script src="http://demo.itsolutionstuff.com/plugin/jquery.js"></script>

<link rel="stylesheet" href="http://demo.itsolutionstuff.com/plugin/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: '/myform/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>

Ok, now we are ready to run our Dependant Dropdown example. Make sure you have some dummy records on posts table. So let's run bellow command on your root directory for quick run:

php -S localhost:8000

Now you can open bellow URL on your browser:

http://localhost:8000/myform

I hope it can help you...






We are Recommending you: