Question: Select2 issues populating select

Question

Select2 issues populating select

Answers 1
Added at 2016-12-29 00:12
Tags
Question

This is my first try with select2 and I'm striking an issue which is probably something basic.

The select control code:

<select class="form-control" id="trade-select" name="trade-select">
     <option>...</option>
</select>

I'm using the following code to fetch data via a coldfusion function:

var options =
    {
        theme: 'bootstrap',
        ajax:
        {       
            url: "/ajax/search-trades.cfm",
            dataType: 'json',
            data: function (params) { return { query: params.term, 'groups_only': true }; },

            processResults: function (data, page)
            { // parse the results into the format expected by Select2.
                alert(data.DATA); // see note further below
                return {results: data.DATA, more: false};
            }

        }
    };

    $('#trade-select').css('width', '100%').select2(options)
        .on('change', function(event)
        {
            if (this.value == '') return;
            $('#trade-select').val('').trigger('change');
        });

The raw JSON data returned from the call to the ajax URL is as follows:

{"COLUMNS":["TRADE_CATEGORY"],"DATA":[["Appliance Repairs"],["Furniture Repair"],["Painting &amp; Decorating"]]}

The alert in the above code returns the following, essentially a comma-delimited list with no brackets or anything:

Appliance Repairs,Furniture Repair, Painting & Decorating

The issue is that the select is not populating with the returned data. I'm guessing it's something related to the format of the returned data.

Not sure if I've provided enough info, so let me know if you need anything else.

For any ColdFusion developer who may have an idea, the following is the ColdFusion template being called via the ajax url. I realise I could make a call directly to the CFC without an intermediary template:

<cfsilent>
<cfparam name="url.groups_only" default="true">
<cfparam name="url.query" default="">

<cfset oSystem = createObject("component","cfcs.system")>
<cfset qTradeCategories = oSystem.getTradeCategories(
    groups_only=url.groups_only,
    query=url.query)>
</cfsilent> 
<cfoutput>#SerializeJSON(qTradeCategories)#</cfoutput>
Answers
nr: #1 dodano: 2016-12-29 01:12

The structure of the results should be a list of objects, where each object must have id and text keys:

[
  {
    'id': 4,
    'text': 'some text'
  },
  {
    'id': 3,
    'text': 'some other text'
  }
]

Since your data is not in that structure - you can make sure you send the correct structure, or generated it in javascript:

results: data.DATA.reduce(function(a, b) { 
      a.push({'id': b[0], 'text': b[0]})
      return a;
 }, [])

data = [["Appliance Repairs"],["Furniture Repair"],["Painting &amp; Decorating"]]

console.log(data.reduce(function(a, b) { 
  a.push({'id': b[0], 'text': b[0]})
  return a;
}, []))

Source Show
◀ Wstecz