up vote 0 down vote favorite
share [fb]

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!

link|improve this question

feedback

2 Answers

up vote 0 down vote accepted

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},...]'.

link|improve this answer
feedback

Your jquery is fine. After several hours I found out that it was the formatting in the 'format' function that was triggering the error.

If you look at the source code at

http://jquery.bassistance.de/autocomplete/demo/json.html

You'll see the following, seemingly inconsequential function

function format(mail) {
    return mail.name + " &lt;" + mail.to + "&gt";
}

If you're leaving out the 'less than' and 'greater than' representations, then you're probably getting the

value is undefinded

error after the first record is looped through in your console. For some strange reason the less than and greater than symbols are significant. Make sure you keep them in your format function.

link|improve this answer
feedback

Your Answer

 
or
required, but never shown

Not the answer you're looking for? Browse other questions tagged or ask your own question.