select2 ajax won't display json data returned
Asked Answered
I

3

5

Here is what the json string looks like that gets returned from my coldfusion page: [{"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 everything is working perfectly but none of the data shows up in the select2 plugin.

Does anyone know what the problem might be? Should it be returning column names or something?

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 };
        }
    }
});
Intima answered 1/3, 2013 at 14:59 Comment(1)
Your data must of format [{"text":"Asante","id":12}, ...] else you need to pass {results: data, text: 'client'}Foresail
F
6

Your data must of format [{"text":"Asante","id":12}, ...] else you need to pass {results: data, text: 'client'}

Foresail answered 1/3, 2013 at 15:34 Comment(0)
I
6

If your json string needs to use something other than "text": "something" then here's the added stuff needed: use formatResults to get the data to show up. 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;
    }
});

Otherwise Arun is right that you just need to use the format [{"id":1,"text":"client"}]

Intima answered 1/3, 2013 at 15:37 Comment(0)
D
2

yes it's too old :) but i needed it today and solved it like this (using Symfony2):

$opts = [];

foreach($items as $item)

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

return new JsonResponse($opts);

the key 'results' is important

Doublet answered 9/12, 2015 at 8:2 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.