Select2 TypeError: data.results is undefined
Asked Answered
U

1

5

Am trying to use Select2 to load remote data using ajax / json but i keep getting an error as:

TypeError: data.results is undefined

My code is :

$('#tags').select2({
                ajax: {
                    url: 'http://localhost:8090/getallusers',
                    dataType: 'json',
                    quietMillis: 100,
                    data: function (term) {
                        return {
                            term: term
                        };
                    },
                    results: function (data) {
                        return data;
                        }

                    }

            });

I really Don’t Understand the Problem !

Unveil answered 29/11, 2013 at 11:54 Comment(2)
How your data value is returned in the result function?Crus
Its like this : [{"id":1,"first_name":"hassan","last_name":"alnator","age":24,"picture":null,"last_in":0,"last_out":0,"username":"halnator","password":"123","user_type":"user"},{"id":2,"first_name":"fareed","last_name":"nam","age":22,"picture":null,"last_in":0,"last_out":0,"username":"fareed","password":"123","user_type":"user"}]Unveil
C
18

Select2 needs the results as a collection of objects with id: and text: attributes.

Like:

[{ 'id': 1, 'text': 'Demo' }, { 'id': 2, 'text': 'Demo 2'}]

Try, to reformat you response like:

$('#tags').select2({
    ajax: {
        url: 'http://localhost:8090/getallusers',
        dataType: 'json',
        quietMillis: 100,
        data: function (term) {
            return {
                term: term
            };
        },
        results: function (data) {
            var myResults = [];
            $.each(data, function (index, item) {
                myResults.push({
                    'id': item.id,
                    'text': item.first_name + " " + item.last_name
                });
            });
            return {
                results: myResults
            };
        }
    }
});
Crus answered 29/11, 2013 at 12:8 Comment(4)
Great Thank you , Now am getting Results but i still cant click on any result and select the one i wont , and i still dont understand the problem ?Unveil
No errors , am getting Results but am trying to click on one so i can select it but its not selecting the resultUnveil
The Problem Was that i was not mapping to the id provided in the json returned , , in the example you have id returned in the json and you are trying to get the 'item.ID' so it should be 'item.id' thnxUnveil
Good catch, and sorry for the typo, I'll fix itCrus

© 2022 - 2024 — McMap. All rights reserved.