Ok, my example is working on my test server, please do the following
, , , "AS TEXT"
$query = $mysqli->query("SELECT id, family AS text FROM family WHERE family LIKE '%$term%'"));
while ($row = mysql_fetch_assoc($query)) {
$return[] = $row;
}
echo json_encode($return);
-, , json- "results"
, json , , - :
{
"results":
[
{
"id": "50",
"text": "Portulacaceae "
},
{
"id": "76",
"text": "Styracaceae "
},
{
"id": "137",
"text": "Dipsacaceae"
}
]
}
php , , .results
results: function (data) {
return { results: data };
}
, ( , / $_GET [] , ), ,
<!DOCTYPE html>
<html>
<head>
<link rel="stylesheet" href="//cdnjs.cloudflare.com/ajax/libs/select2/3.5.2/select2.css">
<script type="text/javascript" src="//cdnjs.cloudflare.com/ajax/libs/jquery/2.1.1/jquery.js"></script>
<script type="text/javascript" src="//cdnjs.cloudflare.com/ajax/libs/select2/3.5.2/select2.js"></script>
</head>
<script>
$(document).ready(function () {
$("#select2_family").select2({
minimumInputLength: 3,
ajax: {
url: "select2.php",
dataType: 'json',
data: function (term) {
return {
term: term,
};
},
results: function (data) {
return { results: data };
}
}
});
});
</script>
<input type="hidden" id="select2_family" name="term" style="width:30%" />
</html>
PHP
<?
$yog = MySqlDatabase::getInstance();
try {
$yog->connect($host, $user, $password, $db_name);
}
catch (Exception $e) {
die($e->getMessage());
}
$term = $_GET['term'];
if (!$term){
$sub = $yog->query("SELECT id, family AS text FROM family");
} else {
$sub = $yog->query("SELECT id, family AS text FROM family where family like '%$term%'");
}
while ($row = mysql_fetch_assoc($sub)) {
$return[] = $row;
}
echo json_encode($return);
?>