Craig
Craig

Reputation: 97

php / jquery autocomplete from mysql table

After referencing many previous questions and answers on this topic, I am still stumped. I am attempting to reference the database that stores a user's contact list. As an initial start, I'm keeping things simple and only allowing reference by email (rather than email, first and last names, etc).

I have the following linked:

<script type="text/javascript" src="http://ajax.googleapis.com/ajax/libs/jquery/1.8/jquery.min.js"></script>
<script type="text/javascript" src="http://ajax.googleapis.com/ajax/libs/jqueryui/1.8.23/jquery-ui.min.js"></script>
<script type="text/javascript">
$(document).ready(function() {
    $( ".emaillist" ).autocomplete({
        source: "contacts.php"}); });
</script>

contacts.php: [UPDATED]

<?php
session_start();
include "scripts/sqlconnect.php";
$id = $_SESSION['id'];
$csql = mysql_query("SELECT * FROM db WHERE id='$id' AND email LIKE '%".mysql_real_escape_string($_GET['term'])."%'");
$contactlist = array();
while($row = mysql_fetch_assoc($csql)){
    $contactlist[] = $row['email'];
}
$contactlist = json_encode($contactlist);
header('Content-Type: application/json');
echo "$contactlist";
?>

And finally the relevant HTML snippet:

<input name="semail" type="text" class="emaillist" id="semail"/>

Any suggestions on what I've done wrong? I can't seem to pinpoint the issue.

Upvotes: 2

Views: 1127

Answers (1)

Sean Bright
Sean Bright

Reputation: 120634

2 things that I notice:

  1. You never output the contents of $contactlist
  2. You aren't setting the appropriate Content-Type header.

So you want to do this:

$contactlist = json_encode($contactlist);
header('Content-Type: application/json');
echo $contactlist;

According to the documentation, the value passed to the AJAX source is called term, so you should be using that in your query, not semail:

...  AND email LIKE "%'. mysql_real_escape_string($_GET['term']) .'%"');
                                                         ^^^^-- Here

Upvotes: 3

Related Questions