Beginner Beginner - 9 days ago 6
Ajax Question

loading data from ajax into html label and listbox not working

I am making an ajax to call data from database with php and i want to load the result in two inputs(label and listbox) in html page,the problem is that it show the value in the label

#FrmCount
but it is not showing anything in the listbox
#FarmersID
..
Here is the ajax

$.ajax({
type:"POST",
url:"AddData.php",
dataType: 'json',
data:
{
'Order_ID': Order_ID,
'Frm_ID':Frm_ID,
'Frm_Wet':Frm_Wet,
'Frm_Dry':Frm_Dry,
'Frm_Fermented':Frm_Fermented,
'Frm_Date':Frm_Date
},
success: function(data)
{
$("#FrmCount").html(data.FarmerCount);
$("#FarmersID").html(data.FarmersID);
},
error: function(jqXHR, textStatus, errorThrown) {
console.log('ERROR', textStatus, errorThrown);
}

})


And this is the php code:

$stmt1 ="SELECT distinct Farm_id FROM ordersfarmers WHERE Order_ID='".$_POST["Order_ID"]."'AND Reply='1'";

$results=$conn->query($stmt1)->fetchAll();
$res=count($results);
foreach ($conn->query($stmt1) as $row)
{
$json = array("FarmerCount" => $res,
"FarmersID" => $row['Farm_id']
);
echo json_encode($json);
}


and the html part

<div>
<select name="FarmersID" id="FarmersID" multiple style="width:280px;height:110px;" onclick="showonmap()">
</select>
</div>
<div>
<label id="FrmCount"></label>
</div>

Answer

With code $("#FarmersID").html(data.FarmersID); you basiclly creating something like:

<select name="FarmersID" id="FarmersID" multiple style="width:280px;height:110px;" onclick="showonmap()">
1 <!-- your id -->
</style>

That's not a proper select format, what you need is create option inside html. For this example you can do:

$("#FarmersID").append('<option value="' + data.FarmerID + '">' + data.FarmerID + '</option>');

But you will always end up with one element. You should return an array (you are not doing that at the moment) or you can build proper html in your php and return that to your javascrip.

Edit:

foreach ($conn->query($stmt1) as $row) 
{
    $farmesIds[$row['Farm_id']] = $row['Farm_id'];
}
$json = array(
    "FarmerCount" => $res,
    "FarmersID" => $farmesIds
);
echo json_encode($json);

And in javascript

$.each(data.FarmersID, function(id, value) {
    $("#FarmersID").append('<option value="' + id + '">' + value + '</option>');
}); 

You can pass something else as value (label or smth?) and keep ID as a key.