views:

326

answers:

1

Hello,

I'm currently working with the jQuery Autocomplete Plugin.

The code they provided in the demonstration is:

 <?php
 $q = strtolower($_GET["q"]);
 $items = array(
"Peter Pan"=>"[email protected]",
"Molly"=>"[email protected]",
 );

  $result = array();
  foreach ($items as $key) {
   if (strpos(strtolower($key), $q) !== false) {
    array_push($result, array(
        "name" => $key
      ));
     }
  }
echo json_encode($result);
 ?>

I'd like to know how I can modify this code to output my own array from my MySQL database.

I've tried on my own modification, but I'm not doing it correctly. This is what I am trying:

$q = strtolower($_GET["q"]);
$sql = "SELECT name from user_info";
require("connection.php");
 $result = mysql_db_query($DBname,$sql,$link) or die(mysql_error()); 

 $rows = array();
 while($r = mysql_fetch_assoc($result)) {
  $rows[] = $r;
foreach ($rows as $key) {
if (strpos(strtolower($key), $q) !== false) {
    array_push($result, array(
        $key
    ));
}
}
}
print json_encode($rows);

And this is my jQuery/Javascript:

    $("#email").autocomplete('emails.php', {
 multiple: false,
 dataType: "json",
 parse: function(data) {
  return $.map(data, function(row) {
   return {
    data: row,
    value: row.name,
    result: row.name
   }
  });
 },
 formatItem: function(item) {
  return format(item);
 }
}).result(function(e, item) {
 $("#content").append("<p>selected " + format(item) + "</p>");
});
});

As a result, Firebug shows that it throws the following error:

  value is undefined

Any help on getting my query setup properly would be greatly aprpeciated. Thanks!

A: 

I think that this occurs because you using a array converted in json, then you need to use how an array too in jquery result. Or you can do a json string without using json, in the format: '[{"name":"john","year":2009},{"name":"tom","year":2000},...]'.

Cesar