jQuery Autocomplete Uncaught TypeError: Can not read property 'length' of undefined [closed]

0

I'm using jQuery autocomplete to grab data from a JSON and show them in as suggestions on the form while typing. It turns out that JSON is not in the format expected by the plugin, so I decided to try to turn it into an array, but it's only in that error.

My code

var arr;
$(document).ready(function getClientedata(){
  $.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 = [
                { value: obj.name, data: obj.id },
        ];      console.log(arr);
      }
    },
    error: function(xhr, e, t){
        alert('Error');
    }
  });
  $('#autocomplete').autocomplete({
      lookup: arr,
      onSelect: function (suggestion) {
          alert('You selected: ' + suggestion.value + ', ' + suggestion.data);
      }
  });
});

I've already prepared a fiddle tbm, for anyone who wants to see.

    
asked by anonymous 28.08.2017 / 04:52

1 answer

2

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);
        }
    });
});
    
28.08.2017 / 05:59