I am using Select2 jquery plugin and I can't get results with json. When looking json response in browser it looks ok. Like this for example:
[{
"id" : "50",
"family" : "Portulacaceae "
}, {
"id" : "76",
"family" : "Styracaceae "
}, {
"id" : "137",
"family" : "Dipsacaceae"
}
]
URL called with ajax in this case is: http://localhost/webpage/json_family.php?term=acac&_=1417999511783
but I can't get that results in select2 input, console says:
Uncaught TypeError: Cannot read property 'length' of undefined
Here is code:
html
<input type="hidden" id="select2_family" name="term" style="width:30%" />
js
$("#select2_family").select2({
minimumInputLength: 3,
ajax: {
url: "json_family.php",
dataType: 'json',
data: function (term) {
return {
term: term,
};
},
results: function (data) {
return { results: data.results };
}
}
});
php
$myArray = array();
if ($result = $mysqli->query("SELECT id,family FROM family WHERE family LIKE '%$term%'")) {
$tempArray = array();
while($row = $result->fetch_object()) {
$tempArray = $row;
array_push($myArray, $tempArray);
}
echo json_encode($myArray);
}
Is there error in code?