1

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?

1
  • 1
    i think you should select the item you want to display not entire database item returned Commented Nov 15, 2018 at 9:21

1 Answer 1

1

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.

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.