I want to make a jQuery UI Autocomplete with multiple values and remote (https://jqueryui.com/autocomplete/#multiple-remote).
Now I have these codes:
JS
$(function() {
function split( val ) {
return val.split( /,\s*/ );
}
function extractLast( term ) {
return split( term ).pop();
}
$("#retr")
.bind( "keydown", function( event ) {
if ( event.keyCode === $.ui.keyCode.TAB &&
$( this ).autocomplete( "instance" ).menu.active ) {
event.preventDefault();
}
})
.autocomplete({
source: function( request, response ) {
$.getJSON( "retr/retr_arry.php", {
term: extractLast( request.term )
}, response );
},
search: function() {
var term = extractLast( this.value );
if ( term.length < 3 ) {
return false;
}
},
focus: function() {
return false;
},
select: function( event, ui ) {
var terms = split( this.value );
terms.pop();
terms.push( ui.item.value );
terms.push( "" );
this.value = terms.join( ", " );
return false;
}
});
});
HTML
<input id="retr" type="text" placeholder="Please select the user(s)">
PHP
//Database connect...
if (isset($_POST["term"])) {
$input_term = $_POST["term"];
} else {
exit;
}
$username = array();
$term2 = '%'.$term.'%';
//SQL
$sql = $db->prepare("SELECT username FROM users WHERE username LIKE ?");
$sql->bind_param('s', $term2);
if ($sql->execute()) {
$sql->store_result();
$sql->bind_result($username);
while ($sql->fetch()) {
$usernames[] = $username;
}
echo (json_encode($usernames));
} else {
exit;
}
The Problem
I get no autocomplete. When I enter up to 5 letters I still get no results.
Edit
After changing POST to GET (in the PHP file), I get results. But the results aren't sorted correctly.
For example: If I enter "adm" I get "SYSTEM". How can I fix this? I think the problem is in the SQL part of the PHP.