Skip to content

Instantly share code, notes, and snippets.

@s-nako

s-nako/index.php Secret

Created March 23, 2021 13:14
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save s-nako/dfd7bb90bcbd64f7a34b76ae339ab26b to your computer and use it in GitHub Desktop.
Save s-nako/dfd7bb90bcbd64f7a34b76ae339ab26b to your computer and use it in GitHub Desktop.
Search suggestion test
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8"/>
<title>test</title>
</head>
<body>
<form action="">
<label>Name:</label>
<input id="input-area" type="text" name="word" list="name-list" autocomplete="off" /><input type="submit" value="Search" />
<datalist id="name-list">
</datalist>
</form>
</body>
<script>
var input_area = document.getElementById('input-area')
input_area.addEventListener("input", search);
function search(){
var ajax = new XMLHttpRequest();
var word = input_area.value;
ajax.open('GET', 'search.php?q='+ word);
ajax.onreadystatechange = function(){
if(ajax.readyState == 4){
var suggest = document.getElementById("name-list");
var result_json_str = ajax.responseText;
var name_list_tags = "";
if(result_json_str != ""){
var result_json_obj = JSON.parse(result_json_str);
for(k in result_json_obj){ // get keys
var item = result_json_obj[k];
name_list_tags += '<option value="' + item['name'] + '">';
}
}
suggest.innerHTML = name_list_tags;
}
}
ajax.send();
}
</script>
</html>
<?php
$dsn = 'mysql:host=localhost;dbname=<server_name>'; // change according to your server name
$username = '<user_name>'; // change according to your server user name
$password = '*******'; // change according to your server password
if ($_GET) {
try {
$query=$_GET["q"];
$dbh = new PDO($dsn, $username, $password);
if($query==""){
echo "";
}
else{
$sql ="select * from user where name like '".$query."%'";
$sth = $dbh->prepare($sql);
$sth->execute();
$result = $sth->fetchAll();
$names = [];
if($result){
foreach ($result as $row) {
// change keys according to your sql table and column
$names += array($row['id'] => array("name" => $row['name'], "age" => $row['age'], "icon" => $row['icon']));
}
echo json_encode($names);
}
else{
echo "";
}
}
}catch (PDOException $e) {
echo "";
exit();
}
}
?>
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment