我想使用 ajax 将选定的属性添加到我的表单中的子类别字段。
如何从函数 edit_book 访问数据以便我可以在外面使用它? 几个小时以来,我一直在努力寻找解决方案……嵌套 ajax 查询是一种解决方案吗?
Form 以模式打开,获取有关所选书籍的数据,根据类别填充子类别但尚未选择所选书籍的子类别。我正在使用 condeigniter3、jquery 和 bootstrap。
/*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');
}
})
}
//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)
/*
this code might be useful
$('.category').change(function() {
var id = $(this).val();
var subcategory_id = "<?php echo $sub_category_id; ?>";
$.ajax({
url: "<?php echo site_url('product/get_sub_category'); ?>",//controller
method: "POST",
data: {
id: id
},
async: true,
dataType: 'json',
success: function(data) {
$('select[name="sub_category"]').empty();
$.each(data, function(key, value) {
if (subcategory_id == value.subcategory_id) {
$('select[name="sub_category"]').append('<option value="' + value.subcategory_id + '" selected>' + value.subcategory_name + '</option>').trigger('change');
} else {
$('select[name="sub_category"]').append('<option value="' + value.subcategory_id + '">' + value.subcategory_name + '</option>');
}
});
}
});
return false;
});
*/