Thursday, May 2, 2013

How to create dynamic select boxes in Codeigniter form using AJAX?

The follownig code clearly explains you how to dynamic select boxes usin AJAX in codeigniter.

VIEW:

<div class="slidtxt">Category :</div>
<div class="slidfield">
<select name="category" id="sc_get">
<option value="ap">Andhrapradesh</option>
<option value="tn">Tamilnadu</option>
<option value="kr">Karnataka</option>
<option value="kl">Kerala</option>
</select>
</div>

<div class="slidtxt">Sub Category :</div>
<div class="slidfield">
<select name="subcat" id="sc_show">

</select>
</div>

<script>
//Script for getting the dynamic values from database using jQuery and AJAX
$(document).ready(function() {
    $('#sc_get').change(function() {

var form_data = {
name: $('#sc_get').val()
};

$.ajax({
url: "<?php echo site_url('controller_name/method'); ?>",
type: 'POST',
dataType: 'json',
data: form_data,
success: function(msg) {
var sc='';
$.each(msg, function(key, val) {
sc+='<option value="'+val.sub_cat+'">'+val.sub_cat+'</option>';
});
$("#sc_show option").remove();
$("#sc_show").append(sc);
}
});
});
});
</script>




CONTROLLER:

public function get_subcat()
{
        $cat=$this->input->post('name');
        $table='subcat';
        $where=array('cat' => $cat);
        $data['sc_get']=$this->admin->get_where_data($table,$where);
        $sc=json_encode($data['sc_get']);
        echo $sc;
}


MODEL:

public function get_where_data($table,$where)
{
        $query=$this->db->get_where($table,$where);
        return $query->result_array();
}





...........................
Have a Great Day.
Keep Smiling....