I am using jquery-ui in this snippet:
$(document).ready(function () {
$(function() {
function log( message ) {
$( "<div>" ).text( message ).prependTo( "#log" );
$( "#log" ).scrollTop( 0 );
}
});
$( "#birds" ).autocomplete({
source: "search.php",
minLength: 4,
select: function( event, ui ) {
log( ui.item ?
"Selected: " + ui.item.value + " aka " + ui.item.id :
"Nothing selected, input was " + this.value );
}
});
});
<div class="ui-widget">
<label for="birds">Birds: </label>
<input id="birds">
</div>
<div class="ui-widget" style="margin-top:2em; font-family:Arial">
Result:
<div id="log" style="height: 200px; width: 300px; overflow: auto;" class="ui-widget-content">
</div>
/div>
and my search.php:
$myarray = ["somelabelvalue","somelabelvalue1","somelabelvalue2","somelabelvalue3"];
echo json_encode($myarray);
BUT when i type: "oems" => every option of the array appear´s! why? It should appear only if i type "some". So where is my mistake in search.php?
this one works correctly: http://jqueryui.com/autocomplete/#remote ..
Greetings!
The problem is that no matter what the user types, you return the same array. What you should do instead, in your PHP code, is to perform some check based on the value given by the user. Note that the jQuery code only lists what gets returned by your PHP code, so filtering is still up to you.
To create the array as you mentioned at the comment, you need to do it like this:
$array = array(
array("id"=>"the id", "label"=>"the label", "value"=>"the value"),
array("id"=>"another id", "label"=>"another label", "value"=>"another value"),
);
After you call echo json_encode($array)
, you will get the desired result.
Echoing what TGO has said, you have to do the filtering in your PHP code. jQuery will make a GET request to the URL you give for the source
option. Therefore in your PHP code you should use the value of $_GET['term']
to decide what JSON array to echo
back. PHP has functions for testing if one string is a substring of another and you can use such a function to filter the array.
$(document).ready(function () {
function log( message ) {
$( "<div>" ).text( message ).prependTo( "#log" );
$( "#log" ).scrollTop( 0 );
}
$( "#birds" ).autocomplete({
source: function( request, response ) {
$.getJSON( "search.php", {
term: request.term
}, response );
},
minLength: 4,
select: function( event, ui ) {
log( ui.item ?
"Selected: " + ui.item.value + " aka " + ui.item.id :
"Nothing selected, input was " + this.value );
}
});
});
<?php
$found_terms = array();
if(isset($_GET['term'])){
$term = trim($_GET['term']);
$myarray = array(
"somelabelvalue",
"somelabelvalue1",
"somelabelvalue2",
"somelabelvalue3"
);
foreach($myarray as $value){
if(strstr($value, $term)){
$found_terms[] = $value;
}
}
}
echo json_encode($found_terms);
?>