Select2 ajax not displaying returned json data

Here's what looks like a string json, which is returned to my page coldfusion: [{"client":"Asante","id":12},{"client":"City of Lancaster","id":14},{"client":"Massey Energy","id":35},{"client":"Northeast Utilities","id":68},{"client":"Washtenaw","id":50}]. Firebug claims that everything works fine, but none of the data is displayed in the select2 plugin.

Does anyone know what the problem is? Should they return column names or something else?

select2 call:

$(".select").select2({
    allowClear: true,
    blurOnChange: true,
    openOnEnter: false,
    ajax: {
        url: "/surveymanagement/admin/client.cfc",
        dataType: 'json',
        data: function (term, page) {
            return {
                method: "GetClientsByName",
                name: term
            };
        },
        results: function (data, page) {
            return { results: data };
        }
    }
});
+5
source share
3 answers

Your data must have a format [{"text":"Asante","id":12}, ...]otherwise you need to go through{results: data, text: 'client'}

+6
source

If your json string should use something other than "text": "something"that, then you need to add additional stuff: use formatResultsto display the data. Here's the fixed version:

$(".select").select2({
    allowClear: true,
    blurOnChange: true,
    openOnEnter: false,
    ajax: {
        url: "/surveymanagement/admin/client.cfc",
        dataType: 'json',
        data: function (term, page) {
            return {
                method: "GetClientsByName",
                name: term
            };
        },
        results: function (data, page) {
            return { results: data };
        }
    },
    formatResult: function (data) {
        return "<div class='select2-user-result'>" + data.client + "</div>";
    },
    formatSelection: function (data) {
        return data.client;
    }
});

, [{"id":1,"text":"client"}]

+6

, :), ( Symfony2):

$opts = [];

foreach($items as $item)

    $opts['results'][] = ['text' => $item->getXyz(), 'id' => $sk->getId()];

return new JsonResponse($opts);

key "results" are important

+1
source

All Articles