/*populate subcats field on cat field change*/
$('#book_cat').change(function(){
var subcat_id = $(this).val();
$("#book_subcat > option").remove();
$.ajax({
type: "POST",
url: "<?php echo site_url('book/populate_subcats'); ?>",//controller
data: {id: subcat_id},
dataType: 'json',
success:function(data){
$.each(data,function(k, v){
var opt = $('<option />');
opt.val(k);
opt.text(v);
$('#book_subcat').append(opt);
});
}
});
});
//get book data
function edit_book(id) {
save_method = 'update';
$('#form')[0].reset(); // reset form on modals
$.ajax({ //Load data from ajax
url: "<?php echo site_url('book/get_row/') ?>" + id,
type: "GET",
dataType: "JSON",
success: function(data) {
$('[name="book_cat"]').val(data.book_cat).trigger('change'); //new
$('[name="book_subcat"]').val(data.book_subcat).trigger('change'); //new
},
error: function(jqXHR, textStatus, errorThrown) {
alert('Error get data from ajax');
}
})
}
//CONTROLLER FILE:
/*******************************************************************/
public function get_row( $id ) {
$data = $this->model->get_row( $id );
echo json_encode( $data );
}
/*******************************************************************/
function populate_subcats() {
$id = $this->input->post( 'id' );
echo( json_encode( $this->model->get_subcats( $id ) ) );
}
//MODEL FILE:
public function get_row( $id ) {
$this->db->from( $this->table );
$this->db->where( $this->field_id, $id );
$query = $this->db->get();
return $query->row();
}
/*******************************************************************/
function get_cats() {
$result = $this->db->get( 'book_cats' )->result();
$id = array( '0' );
$name = array( '-' );
for ( $i = 0; $i < count( $result ); $i++ ) {
array_push( $id, $result[ $i ]->cat_id );
array_push( $name, $result[ $i ]->cat_name );
}
return array_combine( $id, $name );
}
/*******************************************************************/
function get_subcats( $cid = NULL ) {
$result = $this->db->where( 'parent_id', $cid )->get( 'book_subcats' )->result();
$id = array( '0' );
$name = array( '-' );
for ( $i = 0; $i < count( $result ); $i++ ) {
array_push( $id, $result[ $i ]->subcat_id );
array_push( $name, $result[ $i ]->subcat_name );
}
return array_combine( $id, $name );
}
//Database structure:
TABLE `books` (
`book_id`
`book_cat` = refers to table book_cats
`book_subcat` = refers to table book_subcats)
TABLE `book_cats` (
`cat_id`
`cat_name`
TABLE `book_subcats` (
`subcat_id`
`subcat_name`
`parent_id` = refers to table book_cats)