I am trying to pull data from database, the below code works fine and display drop-down of batch number if the batch number has only one record in database, but when i add more stock against same batch number it stops showing the drop down in batch number, on the other hand if i do the same code without json it shows all the batch numbers but i want to handle this with json because i have to pull some other data also from db that i will display in some other divs, kindly help what i am doing wrong.
JQuery/Ajax
<script>
function getBatch(id) {
var product_id = jQuery('#product'+id).val();
jQuery.ajax({
type: 'POST',
url: 'get_Batch.php',
data: { product_id: product_id },
dataType : 'JSON',
success: function(data) {
jQuery('#batch'+id).html(data.batch_option);
jQuery('#available_qty'+id).val(data.avaliable_quantity);
}
});
}
</script>
PHP
<?php
include('includes/config.php');
if(isset($_POST['product_id'])) :
$product_id = $_POST['product_id'];
$get_batch = mysqli_query($conn, "Select * from products JOIN products_stock ON products.p_id='$product_id' AND products.p_id=products_stock.p_id");
if(mysqli_num_rows($get_batch) > 0) :
header('Content-Type: application/json');
while($batch = mysqli_fetch_object($get_batch)) :
$data = [
'batch_option' => "<option value=".$batch -> batch_no.">
".$batch -> batch_no."
</option>",
'avaliable_quantity' => $batch -> p_available
];
echo json_encode($data);
endwhile;
else :
header('Content-Type: application/json');
$data = [
'batch_option' => "<option value='No batch found'> No batch found </option>",
'avaliable_quantity' => 'Not avaliable'
];
echo json_encode($data);
endif;
endif;
?>
If i do like this it will show all record against one batch number in drop down
<?php
include('includes/config.php');
if(isset($_POST['product_id'])) :
$product_id = $_POST['product_id'];
$get_batch = mysqli_query($conn, "Select * from products JOIN products_stock ON products.p_id='$product_id' AND products.p_id=products_stock.p_id");
if(mysqli_num_rows($get_batch) > 0) :
while($batch = mysqli_fetch_object($get_batch)) :
?> <option value="<?php echo $batch -> id; ?>"><?php echo $batch -> id; ?></option> <?php
endwhile;
endif;
endif;
?>
echo json_encode($data);after your while loop. With it in the loop it is echoing multiple json encoded data, which is invalid. You will also need to change$data = ...to$data[] = ...