I'm trying to fetch some school names using autocomplete.But the name list is not appearing. When I type something for example-" uni " it is making a request to sclist.php file like this sclist.php?term=uni and it returns this in response in the network console:
uni
[
"University of Cambridge",
"University of Michigan",
"University of Oxford",
"University of Virginia"
]
I can't seem to find why the list of names is not appearing. This is my first autocomplete implementation. Any help is much appreciated.
the autocom.php file:
<html lang = "en">
<head>
<meta charset = "utf-8">
<title>jQuery UI Autocomplete functionality</title>
<script src = "https://code.jquery.com/jquery-1.10.2.js"></script>
<script src = "https://code.jquery.com/ui/1.10.4/jquery-ui.js"></script>
<!-- Javascript -->
<script>
$(function() {
$( "#automplete" ).autocomplete({
source: 'sclist.php',
autoFocus:true
});
});
</script>
</head>
<body>
<!-- HTML -->
<p>Type something</p>
<input id = "automplete">
</body>
</html>
the sclist.php file:
<?php
require_once('connectToDB.php');
if (isset($_GET['term']))
echo $_GET['term']."\n";
else
echo "not set";
require_once 'connectToDB.php';
$stmt=$portbleDocObj->prepare('SELECT name FROM Institution WHERE name LIKE :prefix ');
$stmt->execute(array( ':prefix'=>$_GET['term']."%") );
$returedData=array();
while ( $row = $stmt->fetch(PDO::FETCH_ASSOC) ) {
$returedData[] = $row['name'];
}
print_r($row);
echo(json_encode($returedData, JSON_PRETTY_PRINT));
?>
Basically I have just done a bit of a tidy up on your original code. Remember, everything you echo or print when you are returning to an AJAX call will go back to the AJAX code to process. So only return what should be returned. Also when talking machine to machine the PRETTY_PRINT is unnecessary
<?php
if ( ! isset($_GET['term'])) {
echo "not set";
} else {
require_once('connectToDB.php');
$stmt = $portbleDocObj->prepare('SELECT name
FROM Institution
WHERE name LIKE :prefix');
$stmt->execute( [':prefix' => $_GET['term']."%"] );
$ret = [];
while ( $row = $stmt->fetch(PDO::FETCH_ASSOC) ) {
$ret[] = $row['name'];
}
echo json_encode($returedData);
}
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.