Wisely D Cruizer Wisely D Cruizer -4 years ago 204
Ajax Question

want to populate datalist using json fetched from php using jquery

HTML code : index.php

<body>
<input type='text' id="gpanel" name="gpanel" list='listid' required>
<datalist id='listid'>
//i want my options here
</datalist>
</body>


JQuery code:

<script>
$(document).ready(function()
{
$.getJSON("php/ajax.php", function(return_data){
$.each(return_data.data, function(key,value){
$("#listid").append(
"<option value="+value.gpanel+">"+"</option>" //gpanel is the title i want in the values
);
});
});
</script>


php code : ajax.php

<?php
include("connection.php");
$result=mysqli_query($conn,"select * from active");//db name
while($rec = mysqli_fetch_assoc($result))
{
$rows[] = $rec;
}
$json_row=json_encode($rows);
echo $json_row;
?>


I dont know where i did wrong! but the datalist is not populating as expected.

Answer Source

In JQuery you are trying to loop throught return_data.data... Use $.each(return_data, function(key,value){ instead.

Or in PHP, add the data dimension :

$json_row=json_encode(array('data' => $rows));
Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download