The mistake Cannot read property 'length' of undefined
can be in Ajax (before autocomplete), which I doubt a little, because it is somewhat improbable jquery ajax return undefined
or it may be due to the variable you passed on lookup
It seems that has 2 problems the scope of the variable arr
may be affecting it and you are incorrectly populating the Array:
arr = [
{ value: obj.name, data: obj.id },
];
This will only get the last result, the right 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>
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery.devbridge-autocomplete/1.4.2/jquery.autocomplete.min.js"></script>
<input type="text" name="country" id="autocomplete">
Alternate way
The alternative way is to use the callback
from the 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);
}
});
});
Man, thank you so much, you saved me here!
– Gustavo de Andrade