Select2 with ajax not returning data

0

I'm trying to make an ajax query to an api to dynamically create a select2.

The api is returning data normally, but only the "No results found" message appears in the select.

HTML

<select name='produtos[]' multiple="multiple" id="selProdutos">
</select>

JQuery

$("#selProdutos").select2({
    maximumSelectionLength: 2,
    ajax: {
        url: 'api/produtos/1',
        type: 'GET',
        dataType: 'json',
        results: function (data) {
            return {
                results: $.map(data, function (item) {
                    return {
                        text: item.name,
                        id: item.id
                    }
                })
            };
        }

    }
}).material_select('destroy')
    
asked by anonymous 05.04.2018 / 11:17

1 answer

1

I have an example here to guide you:

$(obj).select2({
    language: "pt-BR",
    placeholder: "Fornecedores",
    //minimumInputLength: 2,
    maximumSelectionLength: 10,
    tags: false, //permite escrever
    tokenSeparators: [",", " "], //seleciona item automatico
    ajax: {
        url: servidor_api + 'HospitalFornecedor/GetAllByIdHospital',
        dataType: 'json',
        beforeSend: function (xhr) {
            xhr.setRequestHeader("Authorization", "Bearer " + getCookie("token"));
        },
        data: function (params) {
            return {
                FILTRO: params.term,
                //FILTRO: '',
                ID_HOSPITAL: $("#ID_HOSPITAL").val(),
                ID_PACOTE: TryParseInt($("#ID_PACOTE").val(), 0)
            };
        },
        processResults: function (data, params) {
            return {
                results: montaFornecedores(data)
            };
        },
        cache: true
    },
    templateResult: formatResultFornecedor
});
    
06.04.2018 / 17:32