jQuery Autocomplete Uncaught Typeerror: Cannot read Property 'length' of Undefined

Asked

Viewed 1,064 times

0

I’m using jQuery autocomplete to take data from a JSON and show them on as suggestions in the form during 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 is only in this 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 one fiddle tbm, for those who want to see.

1 answer

2


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);
        }
    });
});

Browser other questions tagged

You are not signed in. Login or sign up in order to post.