I'm using AJAX to retrieve information from a database, this was provided for me through another question on StackOverflow, and I've got it working how I want (Minus this one fluke).
Here's how this is set up:
<script>
var input = document.getElementById('search_bar');
input.addEventListener('keypress', function () {
callServer(input);
});
</script>
<script>
function callServer (input) {
xmlhttp = new XMLHttpRequest();
xmlhttp.onreadystatechange = function(){
if (xmlhttp.readyState == 4 && xmlhttp.status == 200){
//return the JSON object
console.log(xmlhttp.responseText);
var arr = JSON.parse(xmlhttp.responseText);
var parentDiv = document.getElementById('items');
parentDiv.innerHTML = "";
//fill the options in the document
for(var x = 0; x < arr.length; x++) {
var option = document.createElement('option');
option.value = arr[x];
//add each autocomplete option to the 'list'
parentDiv.appendChild(option);
};
}
}
xmlhttp.open("GET", "incl/search.php?value="+input.value, true);
xmlhttp.send();
}
Now, when typing into the input field I expect the datalist to update continuously, which it does, the only issue is that the dropdown list is not visible, and I can't access it until I click off of the input field, and then back on the dropdown arrow.
How can I resolve this?
PHP Code for those who are curious:
<?php
include 'connection.php';
$results = array();
if(!isset($_GET['value'])) {
array_push($results, 'No results found.');
die(json_encode($results));
}
$value = $_GET['value'];
$statement = $connection->prepare("SELECT name FROM `item_table`.`items` WHERE `name` LIKE :val LIMIT 5");
$value = '%'.$value.'%';
$statement->bindParam(":val", $value);
if($statement->execute()) {
$rows = 0;
while($row = $statement->fetch()) {
$rows++;
array_push($results, $row['name']);
}
if($rows == 0) {
array_push($results, 'No results found.');
die(json_encode($results));
}
} else {
array_push($results, 'No results found.');
die(json_encode($results));
}
echo json_encode($results);
?>
The JSON being sent to the client is being parsed correctly, just to re-iterate, the issue is that the datalist is not being shown properly.