3
votes

I'm trying to preload an entry into Select2 using a remote ajax call and the initSelection function. My question seems to be similar to this question, however both answers don't work for me.

The call works and returns the correct result in json format, the issue appears to be with the callback not sending the data object in the right format.

j("#selectElement").select2({
    placeholder: "Placeholder text",
    multiple: false,
    minimumInputLength: 1,
    ajax: {
        url: "/getfiles",
        dataType: 'json',
        data: function (term, page) {
            return {
                q: term //search term
            };
        },
        results: function (data, page) {
            return data;
        }
    },
    initSelection: function(element, callback) {
        return j.getJSON("/getfiles?id=" + (element.val()), null, function(data) {
            if (j.isFunction(callback)) {
                //alert(JSON.stringify(data, null, 4));
                return callback(data);
            }
        });
    }
});

When I alert the data object it returns this data:

{
"results": [
    {
        "id": "1",
        "text": "Name of the file"
    }
],
"more": "false"

}

The end result is the text "undefined" being loaded into the select2 input.

I would greatly appreciate any assistance.

Tim

1

1 Answers

2
votes

The solution is to format the callback data like this

return callback(data.results[0]);

Credit goes to this question/answer: Select2 and initSelection callback