[eluser]doob[/eluser]
Maybe this can help you.
View 1
Code:
<select name="state" id="selectstate">
<option value="1">State 1</option>
<option value="2">State 2</option>
<option value="3">State 3</option>
<option value="4">State 4</option>
</select>
<div id="citieswrapper">
<select name="city" id="selectcity">
<option value="">- Select state</option>
</select>
</div>
jQuery
Code:
$("#selectstate").bind("change",function(){
$("#citieswrapper").load("/ajax/get_city", {state_id: $(this).val()} );
});
Controller
Code:
<?php
class Ajax extends Controller {
function Ajax()
{
parent::Controller();
$data = array();
}
function index()
{
}
function get_city()
{
// Load location model
$this->load->model('location_model', 'location');
// Which state to load?
$state_id = $this->input->post('state_id');
$data['cities'] = $this->location->get_cities_in_state($state_id)->result();
$this->load->view('ajax/city_list', $data);
}
}
Model
Code:
<?php
class Location_Model extends Model
{
function Location_Model()
{
parent::Model();
$this->_city_table = "cities";
}
function get_cities_in_state($state_id)
{
$this->db->where('state_id', $state_id);
$this->db->order_by('city_name');
return $this->db->get($this->_city_table);
}
View: ajax/city_list.php
Code:
<select name="city">
<?php foreach($cities as $city) : ?>
<option value="<?php echo $city->city_id; ?>"><?php echo $city->city_name; ?></option>
<?php endforeach; ?>
</select>
DB-table: cities
Code:
id state_id city_name
1 1 City 1
2 1 City 2
3 2 A city in state 2
4 3 Another city in state 2
5 4 City in state 4
6 4 City two in state 4