I have a query in the model as follows :
public function isExistProduct($q)
{
if (!empty($q)) {
$this->db->select("store_item.item_name, store_update_stock.*, sum(qty) as qty, unit_price as up");
$this->db->from('store_update_stock_details');
$this->db->join('store_update_stock', 'store_update_stock_details.update_stock_id=store_update_stock.update_stock_id');
$this->db->join('store_item', 'store_update_stock_details.item=store_item.item_id');
$this->db->where("store_update_stock.status=1 and store_item.item_id= $q");
$this->db->group_by('store_update_stock_details.unit_price','store_item.item_id');
$q1 = $this->db->get();
if ($q1->num_rows() > 0) {
return $q1->result_array();
}
return 0;
}
}
When I set store_item.item_id=1, that returns two records with different unit_prices as follows in the same item (Assume item_name=A).
+-----------+-----+------------+
| item_name | qty | unit_price |
+-----------+-----+------------+
| A | 20 | 8.50 |
| A | 50 | 7.50 |
+-----------+-----+------------+
That is my desired output. It is correct. Then I pass this two records to the following function in the controller.
public function isExistProduct()
{
$id = $this->input->get('q');
$data = $this->Item_model->isExistProduct($id);
if (!empty($data)) {
echo json_encode(array('status' => true, 'data' => $data));
} else {
echo json_encode(array('status' => false));
}
}
After that expecting to show this result through the following JavaScript in my view.
script type="text/javascript">
$(document).on("change", "#item", function () {
$.ajax({
'url': '<?=site_url("item/isExistProduct/?q=")?>' + $('#item').val(),
'method': 'GET',
'success': function (data) {
var jData = JSON.parse(data);
if (jData.status == true) {
jData.data.forEach(data => {
$('#request_table').append('<tr>' +
'<td ><span id="product" >' + jData.data[0].item_name + '</span>' +
'<input type="hidden" id="item_id[]" name="item_id[]" value="' + jData.data[0].item_id + '">' +
'</td>' +
'<td class="text-center">' + jData.data[0].qty + '</td>' +
'<td class="text-center"><input class="form-control text-right" disabled id="sales_price[]" name="sales_price[]" value="' + jData.data[0].up+ '"></td>' +
'<td class="text-center"><input class="form-control text-center rquantity" data-qty-bal="' + jData.data[0].qty + '" autofocus required type="number" step="any" id="qty[]" name="qty[]" ></td>' +
'<td class="text-center" ><i class="fa fa-remove remove" style="cursor: pointer"></i></td>' +
'</tr>');
})
}
},
'error': function () {
}
});
});
</script>
When I run this Script in the view there are two records. But doubled the first record as follows.
+-----------+-----+------------+
| item_name | qty | unit_price |
+-----------+-----+------------+
| A | 20 | 8.50 |
| A | 20 | 8.50 |
+-----------+-----+------------+
What may be going wrong ? Can anyone help me ?
After setting up a function with data as the parameter, the following result is outs.
