Вот мои рабочие решения для CodeIgniter 3.x
Страница контроллера
<?php
defined('BASEPATH') OR exit('No direct script access allowed');
class Controller_name extends CI_Controller {
function __construct()
{
parent::__construct();
}
public function index()
{
$this->load-helper('dropdown');
$dropdownItems = listData('countryTableName','countryId', 'countryName',['where' => ['countryStatus' => 1]]);
$selected = array('null');
$data['countryDropdown'] = form_dropdown('countryId',$dropdownItems,$selected);
$data['stateDropdown'] = form_dropdown('stateId',[], '', 'required="required"');
$this->load->view('page_view',$data);
}
public function get_state()
{
$countryId = $this->input->get('countryId');
$dropdownItems = listData('stateTableName','stateId', 'stateName',['where' => ['countryId' => $countryId,'stateStatus' => 1]]);
$selected = array('null');
echo $stateDropdown = form_dropdown('stateId',$dropdownItems,$selected);
}
}
Поместите этот dropdown_helper.php в каталог Helper
<?php
if(!defined('BASEPATH')) exit('No direct script access allowed');
function listData($table,$name,$value,$options = []) {
$items = array();
$CI =& get_instance();
if(array_key_exists('where',$options)) {
$CI->db->where($options['where']);
}
$query = $CI->db->select("$name,$value")->from($table)->get();
if ($query->num_rows() > 0) {
foreach($query->result() as $data) {
$items[$data->$name] = $data->$value;
}
$default = array('null' => 'Please Select');
$select = $default + $items;
$query->free_result();
return $select;
}
}
На странице просмотра просто эхо
<?php echo $countryDropdown; ?>
<?php echo $stateDropdown; ?>
js файл
$(function(){
$('select[name=countryId]').on('change',function(){
$('select[name=stateId]').html('');
$.ajax({
url: 'controller_name/get_state?countryId='+$(this).val(),
type: "GET",
}).done(function(data) {
$('select[name=stateId]').html(data);
}).fail(function() {
}).always(function() {
});
});
});