Welcome to my website


My name is Richard Watson and I'm a professional PHP developer
from Lurgan in Northern Ireland


jQueryUI Autocomplete & PHP arrays

Posted by richard
Development | 26-02-2018


jqueryui php arrays html forms

Interesting mix - sending a multimimensional PHP array to a jQueryUI autocomplete. Can it be done - easily - and how?

The answer, fortunately enough, is yes! And for an added bonus, it's also relatively simple. For a bonus, we also include how you can chop the results up into slices of 10 (or another value) as well as without limiting the result.

Form


<form method="post" action="./destination" role="form">
<input type="text" id="acField" name="acField" class="form-control"><Br>
<button class="btn btn-success"><span class="fas fa-search"></span> View class</button>
</form>


jQuery (Full result set)
Don't forget to load jQueryUI and jQuery.


<script src="//code.jquery.com/jquery-1.12.4.js"></script>
<script src="//code.jquery.com/ui/1.12.1/jquery-ui.js"></script>
<link rel="stylesheet" href="//code.jquery.com/ui/1.12.1/themes/base/jquery-ui.css">



<script>
$( function() {
var availableTags = <?php echo json_encode($result); ?>;
$( "#acField" ).autocomplete({
source: availableTags
});
});
</script>


jQuery (Limited result set)


<script>
$( function() {
$( "#acField" ).autocomplete({
source: function(request, response) {
var results = $.ui.autocomplete.filter(<?php echo json_encode($result); ?>, request.term);
response(results.slice(0, 10));
}
});
});
</script>


SQL
Note that in this case, I was running against an old MSSQL 2008 instance but it should work fine on MySQL.

 
$sql = "SELECT DISTINCT value FROM database ORDER BY value ASC";
$query = $this->dbh->prepare($sql);
$query->execute();

$result = $query->fetchAll(PDO::FETCH_ASSOC);


And there you go. Relatively simple, too.


You are not signed in


Register or sign-in to post comments
Twitter
Popular tags

Test

project

files

phpmyadmin

frameworks

modal

365

new

directory

board

mysql

GPL