0
votes

I'm using Select2 to populate a dropdown of UK Towns. As the UK Towns DB is huge I figured an AJAX call would be the best way to bring in the data.

I have built a post function and some PHP (In Codeigniter) to catch the query and parse it.

I can see the data is being posted and responded, But my Select2 is not populating with the data.

My jQuery for this is :

 $("#areas").select2(
    {
        tags: [],
        ajax: {
            url: '/profile/get-towns',
            dataType: 'json',
            type: "POST",
            quietMillis: 100,
            data: function (term) {
                return {
                    query: term
                };
            },
            results: function (data) {
                return {
                    results: data.town_id
                }
            },
            cache: true
        },
        escapeMarkup: function (markup) { return markup; }, // let our custom formatter work
        minimumInputLength: 4,
        placeholder         : "Start typing your Town / City",
        maximumSelectionSize: 2
    }
);

My response jSON (Example) is as follows :

[{"town_id":"16994","town":"Hartle"},{"town_id":"16995","town":"Hartlebury"},{"town_id":"16996","town"
:"Hartlebury"},{"town_id":"16997","town":"Hartlebury Common"},{"town_id":"16998","town":"Hartlepool"
},{"town_id":"16999","town":"Hartley"},{"town_id":"17000","town":"Hartley"},{"town_id":"17001","town"
:"Hartley"},{"town_id":"17002","town":"Hartley"},{"town_id":"17003","town":"Hartley Green"},{"town_id"
:"17004","town":"Hartley Green"},{"town_id":"17005","town":"Hartley Mauditt"},{"town_id":"17006","town"
:"Hartley Wespall"},{"town_id":"17007","town":"Hartley Wintney"},{"town_id":"27051","town":"New Hartley"
},{"town_id":"35891","town":"Stowe-by-Chartley"}]

Where am I going wrong? I would ideally like the select dropdown to have the select value = town_id and the select option to be the town name.

Thank You.

2

2 Answers

5
votes

in your select2 configuration:

results: function (data) {
    var res = [];
    for(var i  = 0 ; i < data.length; i++) {
        res.push({id:data[i].town_id, text:data[i].town});
    }
    return {
        results: res
    }
},

becasue select2 wants the results as array of object with keys id and text.

Otherwise you could already returns a well formed object

[
   {"id":"16994","text":"Hartle"},
   {"id":"16995","text":"Hartlebury"},
   {"id":"16996","text":"Hartlebury"},
   {"id":"16997","text":"Hartlebury Common"}
]

then

results: function (data) {
    return {
        results: data
    }
},
-1
votes

On your ajax call, try adding success. Something like this:

success: function( json ) {
   $.each(items, function (i, item) {
       $('#mySelect').append($('<option>', { 
           value: item.value,
           text : item.text 
       }));
   )};
}