Reputation: 829
I have a question about autocomplete input.
There is php code.
<?php
$db = mysqli_connect("localhost", "username", "password", "mydb");
if ($db === false) {
die("ERROR: Could not connect. " . mysqli_connect_error());
} else {
echo "<script>console.log('Polaczenie z baza nawiazane');</script>";
}
$searchTerm = $_GET['term'];
$query = $db->query("SELECT email FROM users WHERE email LIKE '%" . $searchTerm . "%'");
while ($row = $query->fetch_assoc()) {
$data[] = $row['email'];
}
//return json data
echo json_encode($data);
// close connection
mysqli_close($db);
?>
there is my input field.
<input id="email">
and jquery
<script>
$(function() {
$( "#email" ).autocomplete({
source: 'test.php'
});
});
</script>
Problem is that I am getting Json directly on my page - I want to have simple input box with hints(autocomplete) What's wrong?
Upvotes: 1
Views: 103
Reputation: 9201
Looks like you are missing Content-Type
header information when sending the response
from PHP.
I have also noted that you are closing the mysqli connection after the echo. It needs to be the other way around. First close the mysqli connection and then echo.
Check the changed PHP code below,
$db = mysqli_connect("localhost", "username", "password", "mydb");
if ($db === false) {
die("ERROR: Could not connect. " . mysqli_connect_error());
} else {
echo "<script>console.log('Polaczenie z baza nawiazane');</script>";
}
$searchTerm = $_GET['term'];
$query = $db->query("SELECT email FROM users WHERE email LIKE '%" . $searchTerm . "%'");
while ($row = $query->fetch_assoc()) {
$data[] = $row['email'];
}
// close connection
mysqli_close($db);
// adding content type header
header('Content-Type: application/json');
//return json data
echo json_encode($data);
Hope this helps,
Cheers.
Upvotes: 1