The error Cannot read property 'length' of undefined
can be in Ajax (before autocompletion), which I doubt a bit, because it is somewhat improbable that the jquery ajax returns undefined
or it may be due to the variable that you passed in lookup
It seems like 2 problems the scope of arr
may be affecting it and you are populating the Array incorrectly:
arr = [
{ value: obj.name, data: obj.id },
];
This will only get the last result, the correct one should be something like:
$(document).ready(function getClientedata(){
var arr = []; //Cria a array
$.ajax({
type: 'GET',
url: '//jsonplaceholder.typicode.com/users',
dataType: 'json',
success: function(response) {
for(var i = 0; i < response.length; i++) {
var obj = response[i];
arr.push({ value: obj.name, data: obj.id }); //Adiciona item a array
}
},
error: function(xhr, e, t){
alert('Error');
}
});
$('#autocomplete').autocomplete({
lookup: arr,
onSelect: function (suggestion) {
alert('You selected: ' + suggestion.value + ', ' + suggestion.data);
}
});
});
See an example working (without ajax):
$(document).ready(function getClientedata(){
var arr = []; //Cria a array
arr.push({ value: "foo", data: 1 });
arr.push({ value: "bar", data: 2 });
arr.push({ value: "baz", data: 3 });
arr.push({ value: "stack", data: 4 });
arr.push({ value: "overflow", data: 5 });
$('#autocomplete').autocomplete({
lookup: arr,
onSelect: function (suggestion) {
alert('You selected: ' + suggestion.value + ', ' + suggestion.data);
}
});
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script><scriptsrc="https://cdnjs.cloudflare.com/ajax/libs/jquery.devbridge-autocomplete/1.4.2/jquery.autocomplete.min.js"></script>
<input type="text" name="country" id="autocomplete">
Alternative way
The alternative way is to use callback
from lookup, it would look something like this:
$(document).ready(function getClientedata(){
$('#autocomplete').autocomplete({
lookup: function (query, done) {
$.ajax({
type: 'GET',
url: '//jsonplaceholder.typicode.com/users',
dataType: 'json',
success: function(response) {
var result = { "suggestions": [] };
for (var i = 0; i < response.length; i++) {
var obj = response[i];
// Adiciona item a array
result.suggestions.push({
value: obj.name, data: obj.id
});
}
done(result); //Envia a resposta "formatada" pro autocomplete
},
error: function(xhr, e, t){
alert('Error');
}
});
done(result);
},
onSelect: function (suggestion) {
alert('You selected: ' + suggestion.value + ', ' + suggestion.data);
}
});
});