Dynamically dependent dropdown commonly seen in the country, state, and city selection on the webpage. The data on the child element changes according to the value of the parent element.
The process follows the same way if there are more than 2 dropdown elements.
To do this you can either use only PHP or jQuery AJAX.
In this tutorial, I am using jQuery AJAX to make dynamic dependent dropdown in CodeIgniter.
Contents
1. Table structure
I am using three tables –
city
CREATE TABLE `city` ( `id` int(11) NOT NULL PRIMARY KEY AUTO_INCREMENT, `cityname` varchar(80) NOT NULL ) ENGINE=InnoDB DEFAULT CHARSET=latin1;
department
CREATE TABLE `department` ( `id` int(11) NOT NULL PRIMARY KEY AUTO_INCREMENT, `depart_name` varchar(80) NOT NULL, `city` int(3) NOT NULL ) ENGINE=InnoDB DEFAULT CHARSET=latin1;
user_depart
CREATE TABLE `user_depart` ( `id` int(11) NOT NULL PRIMARY KEY AUTO_INCREMENT, `username` varchar(80) NOT NULL, `name` varchar(80) NOT NULL, `email` varchar(80) NOT NULL, `department` int(3) NOT NULL ) ENGINE=InnoDB DEFAULT CHARSET=latin1;
2. Configuration
Navigate to application/config/database.php
and define 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 new Main_model.php
file in application/models/
directory.
Created 3 methods –
- getCity() – Select records from
city
table and return it. - getCityDepartment() – Select records from
department
table according to the city. - getDepartmentUsers() – Select records from
user_depart
table according to the department.
Completed Code
<?php if ( ! defined('BASEPATH')) exit('No direct script access allowed'); class Main_model extends CI_Model { // Get cities function getCity(){ $response = array(); // Select record $this->db->select('*'); $q = $this->db->get('city'); $response = $q->result_array(); return $response; } // Get City departments function getCityDepartment($postData){ $response = array(); // Select record $this->db->select('id,depart_name'); $this->db->where('city', $postData['city']); $q = $this->db->get('department'); $response = $q->result_array(); return $response; } // Get Department user function getDepartmentUsers($postData){ $response = array(); // Select record $this->db->select('id,name,email'); $this->db->where('department', $postData['department']); $q = $this->db->get('user_depart'); $response = $q->result_array(); return $response; } }
4. Controller
Create a new User.php
file in application/controllers/
directory.
Created 3 methods –
- index() – Get cities array list from
Main_model
and pass it as data in$this->view->data('user_view',$data)
. - getCityDepartment() – Handle AJAX request when city is been selected from the
<select>
element. Get department list according to the POST city value and return it. - getDepartmentUsers() – This method also use to handle AJAX request. Select users list according to the POST department value and return it.
Completed Code
<?php defined('BASEPATH') OR exit('No direct script access allowed'); class User extends CI_Controller { public function index(){ // load base_url $this->load->helper('url'); //load model $this->load->model('Main_model'); // get cities $data['cities'] = $this->Main_model->getCity(); // load view $this->load->view('user_view',$data); } public function getCityDepartment(){ // POST data $postData = $this->input->post(); // load model $this->load->model('Main_model'); // get data $data = $this->Main_model->getCityDepartment($postData); echo json_encode($data); } public function getDepartmentUsers(){ // POST data $postData = $this->input->post(); // load model $this->load->model('Main_model'); // get data $data = $this->Main_model->getDepartmentUsers($postData); echo json_encode($data); } }
5. View
Create a new user_view.php
file in application/views/
directory.
Three <select>
element created for city, department, and user selection. The city options are created by looping on the $cities
array.
The other two <select>
elements for department and user will be empty. They were auto-filled as per options selection with jQuery.
Defined change
event in city and department <select>
element.
jQuery –
City Change
When city dropdown option is been changed then send an AJAX request to index.php/User/getCityDepartment
and pass city value as data
.
On successful callback remove all options except first from the department and user dropdown.
Append response data on department element.
Department Change
When department dropdown option is been changed then send an AJAX request to index.php/User/getDepartmentUsers
and pass department value as data
.
On successful callback remove all options except first from the user dropdown.
Append response data on the user dropdown.
Completed Code
<!doctype html> <html> <body> <table border='0'> <!-- City --> <tr> <td>City</td> <td> <select id='sel_city'> <option>-- Select city --</option> <?php foreach($cities as $city){ echo "<option value='".$city['id']."'>".$city['cityname']."</option>"; } ?> </select> </td> </tr> <!-- Department --> <tr> <td>Department</td> <td> <select id='sel_depart'> <option>-- Select deparment --</option> </select> </td> </tr> <!-- User --> <tr> <td>User</td> <td> <select id='sel_user'> <option>-- Select user --</option> </select> </td> </tr> </table> <!-- Script --> <script src="https://ajax.googleapis.com/ajax/libs/jquery/3.6.0/jquery.min.js"></script> <script type='text/javascript'> // baseURL variable var baseURL= "<?php echo base_url();?>"; $(document).ready(function(){ // City change $('#sel_city').change(function(){ var city = $(this).val(); // AJAX request $.ajax({ url:'<?=base_url()?>index.php/User/getCityDepartment', method: 'post', data: {city: city}, dataType: 'json', success: function(response){ // Remove options $('#sel_user').find('option').not(':first').remove(); $('#sel_depart').find('option').not(':first').remove(); // Add options $.each(response,function(index,data){ $('#sel_depart').append('<option value="'+data['id']+'">'+data['depart_name']+'</option>'); }); } }); }); // Department change $('#sel_depart').change(function(){ var department = $(this).val(); // AJAX request $.ajax({ url:'<?=base_url()?>index.php/User/getDepartmentUsers', method: 'post', data: {department: department}, dataType: 'json', success: function(response){ // Remove options $('#sel_user').find('option').not(':first').remove(); // Add options $.each(response,function(index,data){ $('#sel_user').append('<option value="'+data['id']+'">'+data['name']+'</option>'); }); } }); }); }); </script> </body> </html>
6. Demo
7. Conclusion
In this tutorial, I showed you how you can use AJAX to make dynamic dependent dropdown. Follow the same way if there is the other type of element e.g. textbox, textarea, etc. but you need to modify the script.
If you found this tutorial helpful then don't forget to share.
Dear sir
I need ur above work in datagrid form where multiple rows are available and each row contain city ,department and user in dependent combobox.Thanks for ur immediate response.
Code not working
change in controller
$postData= $this->input->post(); into $postData = $this->input->post(‘sel_city’);
for the model
$this->db->where(‘city’, $postData[‘city’]); with $this->db->where(‘city’, $postData);
Hi Cris,
The code is working fine and I rechecked it. In the example, I have not posted “sel_city”. From $.ajax I posted {city: city} as data when
oh ok. but when i try that its not working hehe thanks btw mate!
Класс. Давно искал такое, нашел все таки. Thanks a lot
Thanks.
so good ..thanks…
Glad it was helpful.
thanks..that working for me.. (“,)9
This saved my life ! thank u verry much !!!
I followed every instruction and copy pasted the codes but it’s not working. after choosing a city, department is not being populated, it’s empty. hope you can help. thanks
Thanks for the help Yogesh. I’ll give you 5 stars for the responsiveness and quality
Thanks.
I followed every instruction and copy pasted the codes but it’s not working. after choosing a city, department is not being populated, it’s empty. hope you can help
Hi Rahul,
Is there any error you are viewing in Browser console.
Good Job
Department list is not showing even after selecting city and there is no error in browser console also.
Add following code in $.ajax success function to check what data is returning –
console.log(‘success : ‘ + JSON.stringify(response) );
Response view in the browser console.
Dear Yogesh Singh,
The core doesn’t work. However there are no error in the browser console too.
Appreciate if you could help, thank you.
Add following code in both $.ajax request to check it is working or not –
error: function(response){
console.log(‘error : ‘ + JSON.stringify(response) );
}
and also add console.log(‘success : ‘ + JSON.stringify(response) ); in $.ajax success function to know what it is returning if their is no error.
Check response in the browser console.
// City change
$(‘#sel_city’).change(function(){
var city = $(this).val();
the variable city here is exactly what??
I tried this code for countries and their cities, but i am only getting countries but not the associated cities.
Hi Rashmi
var city stores selected option value which is city-id.
You need to use country-id to fetch cities of the selected country with AJAX.
followed every instruction and copy pasted the codes but it’s not working. after choosing a city, department is not being populated, it’s empty. hope you can help me, plz
Is there any error displaying in the browser console.
hey yogesh i worked on your code but its not working for me..please help me
why i cant see the demo, it says “A PHP Error was encountered” and “database error occurred”
The demo is now working I have fixed the issue.
Thank you for sharing this, the code work, how to display the selected value after save it into db. all dependent value is empty on my view page, but the id is stored in the db, pls guide newbie here
hi yogesh,
can you explain?!?!?!?
in this same eg. how to retrive and show on dropdown for a registration form.
Hi joal,
In the first dropdown, I am adding the options with PHP.
Defined change event on the first dropdown. When option selected then send AJAX request to controller method for fetching records.
On successful callback loop on the response and add options in the second dropdown.
Similarly, defined change event on the third drop-down. On change send AJAX request and add options in the third dropdown on successful callback.
Hi.Thanks you for share your knowledge. i need your help that how i can store dropdown value name not id in to database so what code will b use?
Hi Arif,
You can read <option > text with $(“#sel_user option:selected”).text(); and use it in INSERT query.
thanx Yogesh
You’re welcome.
I followed every instruction and copy pasted the codes but it’s not working. after choosing a city, department is not being populated, it’s empty. hope you can help me, plz
Hi Surya,
I any error displaying in the browser console?
how to display user details such as email too with user
Hi Vishnu,
You need to send AJAX request to get user details on user dropdown change event.
I was struggling with this for my project using codeigniter 3. After tirelessly searching on the web “w3s ajax php” “php send ajax to php”… I then searched “ajax dropdown codeigniter” and yours was the 3rd result. Thank you so much. My project is due in 5 days and you darn saved my arse.