I have this form field:
echo $this->Form->control('customer', ['id' => 'Autocomplete', 'empty' => false, 'required' => true]);
I am trying to implement autocomplete with search in db. So here is the jquery code:
<script type="text/javascript">
$("#Autocomplete").keyup(function(){
$(this).val($(this).val().toLowerCase());
});
</script>
<script type="text/javascript">
$( function() {
$( "#Autocomplete" ).autocomplete({
minLength: 1,
source: function( request, response ) {
$.ajax({
url: '/app/tasks/getAll',
dataType: 'json',
data:{
text : $('#Autocomplete').val()
},
success: function (data)
{
var lenlen=data.length;
var res=[];
for(var i=0;i<lenlen;i++){
res[i]=data[i].company;
//console.log(data[i].company);
}
response( $.map( data, function( item )
{
console.log(item.company);
return{
label: item.company,
value: item.company,
id: item.company
}
}));
}
});
},
select: function( event, ui ) {
event.preventDefault();
$('#Autocomplete').val(ui.item.label);
},
});
});
// A custom jQuery method for placeholder text:
$.fn.defaultText = function(value){
var element = this.eq(0);
element.data('defaultText',value);
element.focus(function(){
if(element.val() == value){
element.val('').removeClass('defaultText');
}
}).blur(function(){
if(element.val() == '' || element.val() == value){
element.addClass('defaultText').val(value);
}
});
return element.blur();
}
And this is the code in the controller to search the database:
public function getAll() {
$this->viewBuilder()->layout(false);
$this->autoRender = false;
$data = $this->request->getQuery('text');
$results = TableRegistry::get('Customers')->find('all', ['fields' => ['id', 'company', 'name', 'surname'],
'conditions' => [
'OR' => [
'LOWER(name) LIKE' => '%'.$data.'%',
'LOWER(company) LIKE' => '%'.$data.'%',
'LOWER(surname) LIKE' => '%'.$data.'%'
]
]]);
$response = array();
$i = 0;
foreach($results as $result){
$response[$i]['id'] = $result['id'];
$response[$i]['company'] = $result['company'];
$i++;
}
echo json_encode($response);
}
But while I can see that the results are fetched correctly from the database in console.log, they are not displayed as a dropdown under the field to choose one of them.It doesnt work only when I load the form via modal, if I open the form directly then autocomplete works
How I can fix that?
EDIT
When I open the form I get this error also:
toolbar.js?1550138303:83 [Deprecation] Synchronous XMLHttpRequest on the main thread is deprecated because of its detrimental effects to the end user's experience. For more help, check https://xhr.spec.whatwg.org/.