Codeigniter Dependent country state city dropdown using jQuery Ajax with MySQL
In this tutorial, I am going to explain the dynamic dependent country state and city dropdown using jQuery Ajax in Codeigniter and MySQL. Dynamic dependent select box is used to implement country state city dropdown functionality. Using jQuery Ajax in Codeigniter and MySQL, you can easily implement a dynamic dependent dropdown without page refresh. We will cover this tutorial in easy steps with a live demo to develop a complete dynamic dependent dropdown. We will also provide to download source code of the live demo.
Step 1: Create MySQL Database and Tables
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 |
<?php //Table structure for table `countries` CREATE TABLE `countries` ( `id` int(11) NOT NULL, `sortname` varchar(3) NOT NULL, `name` varchar(150) NOT NULL, `slug` varchar(100) DEFAULT NULL ) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4; ALTER TABLE `countries` ADD PRIMARY KEY (`id`); ALTER TABLE `countries` MODIFY `id` int(11) NOT NULL AUTO_INCREMENT, AUTO_INCREMENT=1; //Table structure for table `states` CREATE TABLE `states` ( `id` int(11) NOT NULL, `name` varchar(30) NOT NULL, `country_id` int(11) NOT NULL DEFAULT '1' ) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4; ALTER TABLE `states` ADD PRIMARY KEY (`id`); ALTER TABLE `states` MODIFY `id` int(11) NOT NULL AUTO_INCREMENT, AUTO_INCREMENT=1; //Table structure for table `cities` CREATE TABLE `cities` ( `id` int(11) NOT NULL, `name` varchar(30) NOT NULL, `state_id` int(11) NOT NULL ) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4; ALTER TABLE `cities` ADD PRIMARY KEY (`id`); ALTER TABLE `cities` MODIFY `id` int(11) NOT NULL AUTO_INCREMENT, AUTO_INCREMENT=1; ?> |
Step 2: Create a model file
Create a model file named “Site.php” inside “application/models” folder.
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 |
<?php /* * To change this license header, choose License Headers in Project Properties. * To change this template file, choose Tools | Templates * and open the template in the editor. */ /** * @package Razorpay : CodeIgniter Site * * @author TechArise Team * * @email info@techarise.com * * Description of Site Controller */ if (!defined('BASEPATH')) exit('No direct script access allowed'); class Site extends CI_Model { private $_countryID; private $_stateID; // set country id public function setCountryID($countryID) { return $this->_countryID = $countryID; } // set state id public function setStateID($stateID) { return $this->_stateID = $stateID; } public function getAllCountries() { $this->db->select(array('c.id as country_id', 'c.slug', 'c.sortname', 'c.name as country_name')); $this->db->from('countries as c'); $query = $this->db->get(); return $query->result_array(); } // get state method public function getStates() { $this->db->select(array('s.id as state_id', 's.country_id', 's.name as state_name')); $this->db->from('states as s'); $this->db->where('s.country_id', $this->_countryID); $query = $this->db->get(); return $query->result_array(); } // get city method public function getCities() { $this->db->select(array('i.id as city_id', 'i.name as city_name', 'i.state_id')); $this->db->from('cities as i'); $this->db->where('i.state_id', $this->_stateID); $query = $this->db->get(); return $query->result_array(); } } ?> |
Step 3: Create a controller file
Next create a controller file named “Location.php” inside “application/controllers” folder.
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 |
<?php /* * To change this license header, choose License Headers in Project Properties. * To change this template file, choose Tools | Templates * and open the template in the editor. */ /** * Description of Location Controller FrontEnd * * @author Jaeeme */ if (!defined('BASEPATH')) exit('No direct script access allowed'); class Location extends CI_Controller { public function __construct() { parent::__construct(); $this->load->model('Site', 'location'); } // get state names public function index() { $data['page'] = 'country-list'; $data['title'] = 'country List | TechArise'; $data['geCountries'] = $this->location->getAllCountries(); $this->load->view('location/index', $data); } // get state names public function getstates() { $json = array(); $this->location->setCountryID($this->input->post('countryID')); $json = $this->location->getStates(); header('Content-Type: application/json'); echo json_encode($json); } // get city names function getcities() { $json = array(); $this->location->setStateID($this->input->post('stateID')); $json = $this->location->getCities(); header('Content-Type: application/json'); echo json_encode($json); } } ?> |
Step 4: Change Route file
So open “application/config/routes.php” file and add code like as bellow:
1 2 3 4 |
<?php // create routes $route['default_controller'] = 'location/index'; ?> |
Step 5: Create a view< file
Create a view file named “index.php” inside “application/views/emp” folder
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 |
<?php $this->load->view('templates/header'); ?> <div class="row"> <div class="col-lg-12"> <h2>Codeigniter Dependent country state city dropdown using jQuery Ajax with MySQL</h2> </div> </div> <div class="row"> <div class="col-lg-12"> <a href="#" class="pull-right btn btn-info btn-xs" style="margin: 2px;"><i class="fa fa-mail-reply"></i> Back To Tutorial</a> </div> </div> <br> <div class="row"> <div class="col-lg-12"> <span id="success-msg"></span> </div> </div> <form class="dynamic-dependent-frm" id="dynamic-dependent-frm"> <div class="row"> <div class="col-lg-12"> <div class="form-group"> <select title="Select Country" name="regcountry" class="form-control" id="country-name"> <option value="">Select Country</option> <?php foreach ($geCountries as $key => $element) { echo '<option value="'.$element['country_id'].'">'.$element['country_name'].'</option>'; } ?> </select> </div> </div> </div> <div class="row"> <div class="col-lg-12"> <div class="form-group"> <select title="Select State" name="state_name" class="form-control" id="state-name"> <option value="">Select State</option> </select> </div> </div> </div> <div class="row"> <div class="col-lg-12"> <div class="form-group"> <select title="Select City" name="city_name" class="form-control" id="city-name"> <option value="">Select City</option> </select> </div> </div> </div> </form> <?php $this->load->view('templates/footer'); ?> |
Step 5: Create a file
Create a view file named “custom.js inside “assets/js” folder
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 |
// get state jQuery(document).on('change', 'select#country-name', function (e) { e.preventDefault(); var countryID = jQuery(this).val(); getStatesList(countryID); }); // get city jQuery(document).on('change', 'select#state-name', function (e) { e.preventDefault(); var stateID = jQuery(this).val(); getCityList(stateID); }); // function get All States function getStatesList(countryID) { $.ajax({ url: baseurl + "location/getstates", type: 'post', data: {countryID: countryID}, dataType: 'json', beforeSend: function () { jQuery('select#state-name').find("option:eq(0)").html("Please wait.."); }, complete: function () { // code }, success: function (json) { var options = ''; options +='<option value="">Select State</option>'; for (var i = 0; i < json.length; i++) { options += '<option value="' + json[i].state_id + '">' + json[i].state_name + '</option>'; } jQuery("select#state-name").html(options); }, error: function (xhr, ajaxOptions, thrownError) { console.log(thrownError + "\r\n" + xhr.statusText + "\r\n" + xhr.responseText); } }); } // function get All Cities function getCityList(stateID) { $.ajax({ url: baseurl + "location/getcities", type: 'post', data: {stateID: stateID}, dataType: 'json', beforeSend: function () { jQuery('select#city-name').find("option:eq(0)").html("Please wait.."); }, complete: function () { // code }, success: function (json) { var options = ''; options +='<option value="">Select City</option>'; for (var i = 0; i < json.length; i++) { options += '<option value="' + json[i].city_id + '">' + json[i].city_name + '</option>'; } jQuery("select#city-name").html(options); }, error: function (xhr, ajaxOptions, thrownError) { console.log(thrownError + "\r\n" + xhr.statusText + "\r\n" + xhr.responseText); } }); } |