I 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.
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));
So simple!
HTML Code
<form>
<h3>Search :</h3><br>
<input type="text" id="search" list="datalist">
<datalist id="datalist"></datalist>
</form>
jQuery Code
$("document").ready(()=>{
$("#search").keyup(()=>{
let list = $("#search").val();
$("#datalist").empty();
if(list!=""){
$.getJSON("http://localhost/file.php?search="+list,(data)=>{
$.each(data,(k,v)=>{
$("#datalist").append("<option value="+v.gpanel+"></option>");
});
});
}
});
});
PHP Code file.php
$base = new PDO("mysql:host=URL;dbname=DATABASE_NAME","USER","PASSWORD");
$something = $_GET["search"];
$req = $base->prepare("SELECT * FROM your_table WHERE Row_name LIKE '%".$something."%'");
$req->execute();
$tab = $req->fetchAll(PDO::FETCH_ASSOC);
echo json_encode($tab);