Populate Dynamic Dropdowns List in Codeigniter



PHP Snippet 1:

<?php

class Index extends CI_Controller {

    public function __construct() {
        parent::__construct();
        $this->load->helper('url_helper');
        $this->load->model('countries_model');
    }

    public function index() {
        $query = $this->db->query('SELECT id,name FROM countries');
        $data['countries'] = $query->result_array();
        $this->load->view('index/index', $data);
    }

    public function cities() {
        $country_id = $this->input->post('country_id');
        $query = $this->db->query('SELECT id,name FROM cities WHERE country_id=' . $country_id);
        $data['cities'] = $query->result_array();
        $this->load->view('index/cities', $data);
        echo $country_id;
    }

}

PHP Snippet 2:

<?php

class Countries_model extends CI_Model {

    public function __construct() {
        $this->load->database();
    }

}

PHP Snippet 3:

<!DOCTYPE html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
<title>Dymanic Selects</title>
<script type="text/javascript" src="<?php echo base_url(); ?>js/jquery.js" ></script>

<script type="text/javascript">
$(document).ready(function(){
    $('#sl_countries').change(function(){
            $('#sl_cities').load("<?php echo site_url('index/cities') ?>",{country_id:$(this).val()});
        }); 
});
</script>

</head>
<body>
    <label>Countries</label>
    <select id="sl_countries">
        <?php foreach($countries as $c):?>
        <option value="<?php echo $c['id']?>"><?php echo $c['name']?></option>
        <?php endforeach;?>
    </select>

    <label>Cities</label>
    <select id="sl_cities"></select>
</body>
</html>

PHP Snippet 4:

<?php foreach ($cities as $c): ?>
    <option value="<?php echo $c['id'] ?>"><?php echo $c['name'] ?></option>
<?php endforeach; ?>

PHP Snippet 5:

<select id="sl_countries">
        <?php foreach($countries as $c):?>
        <option value="<?php echo $c['id']?>"><?php echo $c['name']?></option>
        <?php endforeach;?>
    </select>