This is an AJAX example to generate dependant drop down (select):
CONTROLLER: dropdown.php
<?php
class Dropdown extends Controller {
function Dropdown()
{
parent::Controller();
$this->load->helper(array('form', 'url'));
}
function index($options=null)
{
$data['first_options'] = array(
'1' => 'Italy',
'2' => 'Brazil',
);
$options!=null ? $data['options'] = $options : '';
$this->load->view('ddown', $data);
}
//-------------------------------------------------------------
function prova()
{
//this is for a demo and uses arrays
//you can also build options with DB queries
$data['options_1'] = array('1'=>'topolino',
'2'=>'pippo',
'3'=>'minnie',
'4'=>'paperone');
$data['options_2'] = array('1'=>'brazilian',
'2'=>'girls',
'3'=>'rock!');
$options ='';
if ($_POST['first_select']!='') //$_POST['first_select'] is the post variable you sent via AJAX call
{
$parent = $_POST['first_select'];
switch($parent)
{
case 1:
$data['options'] = $data['options_1'];
break;
case 2:
$data['options'] = $data['options_2'];
break;
}
foreach ($data['options'] as $key=>$value)
{
$options.= '<option value="'.$key.'" class="dynamic">'.$value.'</option>';
}
echo $options;
}
}
}
?>
VIEW: ddown.php
<html>
<head>
<title>Dynamic Dropdown</title>
>script src="http://www.your_path/jquery.js" type="text/javascript"></script>
>script type="text/javascript">
function test()
{
var valore = $("#first_select").val();
$.ajax({
url: "<?=base_url();?>dropdown/prova",
global: false,
type: "POST",
async: false,
dataType: "html",
data: "first_select="+ valore, //the name of the $_POST variable and its value
success: function (response) //'response' is the output provided by the controller method prova()
{
//counts the number of dynamically generated options
var dynamic_options = $("*").index( $('.dynamic')[0] );
//removes previously dynamically generated options if they exists (not equal to 0)
if ( dynamic_options != (-1)) $(".dynamic").remove();
$("#second_select").append(response);
$(".first").attr({selected: ' selected'});
}
});
return false
}
</script>
</head>
<body>
<h1>Dynamic Dropdown</h1> by <a href="http://www.4webby.com">4webby.com</a>
<?=form_open('')?>
<p>
<select name="first_select" id="first_select" onchange="test()">
<option value="0">browse</option>
<option value="0">----------------</option>
<?php
if (isset($first_options))
{
foreach ($first_options as $key=>$value)
{
echo '<option value="'.$key.'">'.$value.'</option>';
}
}
?>
</select>
<select name="second_select" id="second_select">
<option value="0" class="first">browse</option>
<option value="0">----------------</option>
</select>
</p>
<?=form_close()?>
</body>
</html>
What I found difficult in the beginning was to debug the ajax calls. For this purpose I suggest you FireBug