I have built a simple search tool for my Web App to search through my client database. It returns form submit buttons in a dropdown so that, when a selection is made, the selected clients ID is passed in a POST to the following page. The following page receives this POST and populates with all of the stored information about that client. This works the way I need it to for the most part, but I have a couple questions.
1) most autocompletes/autosuggests that I have seen examples of return JSON data as the results. Is using JSON inherently a smoother or safer process for this?
2) my search results (form buttons) display in a dropdown but are not navigable via TAB or ARROW keys. What is needed to add this accessibility? I tried to add TabIndex to the buttons but that did nothing.
I arrived at this particular solution for my need of a search function after failing miserably to understand some of the pre-packaged Autocomplete solutions out there. They seemed much more complex than what I needed for this Web App.
Here is what I am using.
HTML:
<div class="row">
<div class="col-12">
<input onKeyUp="myFunction()" type="text" id="searchterm" placeholder="Search for existing client">
<div class="searchResults" id="results"></div>
<script>document.getElementById("results").style.visibility='hidden';</script>
<script type="text/javascript" src="js/watchdog.js"></script>
</div>
</div>
JAVASCRIPT:
function myFunction() {
var input = document.getElementById("searchterm").value;
if (input && input.length >= 2) {
$.ajax({
type: "POST",
url: "searchengine.php",
data: {input : input},
success: function(data) {
if (data) {
document.getElementById("results").style.visibility='visible';
document.getElementById("results").innerHTML = data;
}
else {
document.getElementById("results").style.visibility='hidden';
}
}
});
}
else {
document.getElementById("results").style.visibility='hidden';
return false;
}
}
PHP:
<?php
include ('connect.php');
$input = trim($_POST['input']);
$input = htmlspecialchars($input);
$equiv = '%' . $input . '%';
// prepare stmt, bind param, execute
$stmt = $conn->prepare("SELECT client_id, firstname, lastname, city, state FROM client WHERE firstname LIKE ? OR lastname LIKE ?");
$stmt->bind_param("ss", $equiv, $equiv);
$stmt->execute();
$stmt->bind_result($client_id, $firstname, $lastname, $city, $state);
while ($stmt->fetch()) {
echo "
<form name=\"clientSearchResults\" action=\"client.php\" method=\"post\">
<input name=\"client_id\" value=\"$client_id\" type=\"hidden\">
<div class=\"wrapper\">
<input style=\"height: 25px;\" type=\"submit\" value=\"$firstname $lastname - $city, $state\"></input>
</div>
</form>
";
}
// close statement
$stmt->close();
include ('disconnect.php');
?>