Select2 with ajax not returning data

Asked

Viewed 368 times

0

I am 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 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')

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

Browser other questions tagged

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