I have the following
<form action="" method="post">
<input type="text" class="auto" name="search" autocomplete="off">
</form>
<script>
$(document).ready(function($){
$('.auto').autocomplete({
source:'connect.php',
minLength:1
});
});
</script>
And connect.php I KNOW I have to sanitize $term before inputting it into my query.
if(isset($_GET['term'])) {
require "db.php";
$con = mysqli_connect("$host","$user","$password","$db");
if (mysqli_connect_errno())
{
echo "Failed to connect to MySQL: " . mysqli_connect_error();
}
$term = $_GET['term'];
$query = "SELECT `name` FROM `products` WHERE `name` LIKE '%$term%'";
$result = mysqli_query($con, $query);
while ($row = mysqli_fetch_array($result)) {
echo json_encode($row);
}
}
If I typed M
in the input field and use chrome tools to inspect the response, I get this.
{"0":"MacBook Pro 13-inch","name":"MacBook Pro 13-inch"}{"0":"MacBook Pro 15-inch","name":"MacBook Pro 15-inch"}{"0":"MacBook Air 13-inch","name":"MacBook Air 13-inch"}{"0":"MacBook Air 11-inch","name":"MacBook Air 11-inch"}{"0":"iMac 21.5-inch","name":"iMac 21.5-inch"}{"0":"iMac 27-inch","name":"iMac 27-inch"}{"0":"Mac Pro Quad-Core","name":"Mac Pro Quad-Core"}{"0":"Mac Pro 6-Core","name":"Mac Pro 6-Core"}
However, for some reason, it states 'No results found' on the page even though there is?
The output your php-script creates is no valid json - you have to wrap the individual objects in an array:
[{"0":"MacBook Pro 13-inch","name":"MacBook Pro 13-inch"}, {"0":"MacBook Pro 15-inch","name":"MacBook Pro 15-inch"}, {"0":"MacBook Air 13-inch","name":"MacBook Air 13-inch"}, {"0":"MacBook Air 11-inch","name":"MacBook Air 11-inch"}, {"0":"iMac 21.5-inch","name":"iMac 21.5-inch"}, {"0":"iMac 27-inch","name":"iMac 27-inch"}, {"0":"Mac Pro Quad-Core","name":"Mac Pro Quad-Core"}, {"0":"Mac Pro 6-Core","name":"Mac Pro 6-Core"}]
Modify your PHP-script like this:
$result = array();
while ($row = mysqli_fetch_array($result)) {
$result[] = $row;
}
json_encode($result);
In addition to that - your output should have the properties id, value and label, not just "0".