How to pass both id and text value

How do I get both values id & text?
I have a json datafile:

“results”: [
{
“id”: “123”,
“text”: “lion”
},
{
“id”: “456”,
“text”: “tiger”
},

I want to pass both values to my cgi script

code snippet:

. . .  

script1.js:
(function() {
// init select 2
$(’#getDevs’).select2({
ajax: {
type: “GET”,
url: “/RED/data/devices.json”,
dataType: ‘json’,
data: function (params) {
var query = {
search: params.term,
page: params.page || 1
}

  // Query parameters will be ?search=[term]&page=[page]
  return query;

            //return {
            //   q: params.term,
            //   page: params.page
            //};
        },  
        processResults: function(data, params) {
            params.page = params.page || 1
            return { 
              results: _.filter(data.results, function(e) {
                 return e.text.toUpperCase().indexOf(params.term.toUpperCase()) >= 0;
              }),
              pagination: { 
                more: (params.page * 30) < data.results.length
              }
            };
        },
        cache: true
    },
    placeholder: "Enter an animal",
    multiple: true,
    allowClear: true,
    minimumInputLength: 3

})
})();
here’s what gets passed:
https://xxxxxxxxxxxx/cgi-bin/red/do_rediscovery.cgi?name=123

How can I also pass this id value

example:
If I select lion, I would like to pass name=lion&id=123

Is it possible?

Thanks

It is not possible without writing your own AJAX Adapter. Since you own/control the data, Select2 expects that your server knows what the ID values mean.

However, you don’t have to use purely numerical values for the id properties; any unique value will work. So you could set your id properties like this:

{
  results: [
    { 
      "id": "123:lion", "text": "lion",
      "id": "456:tiger", "text": "tiger"
    }
  ]
}

Then your CGI script will get called like: https://…/cgi-bin/red/do_rediscovery.cgi?name=123%3Alion (the colon in “123:lion” gets URL-encoded as %3A).

Note that if you don’t want to keep the “combined” id values in your server-side data source, you can create them in your processResults callback:

   // ...
   return {
      results: _.map(_.filter(/* your filter logic */), function(r) { 
                    return { id: r.id + ":" + r.text, text: r.text}; 
                }),
      pagination: { ... }
    };
    // ...

Thanks! that works perfectly :slight_smile:

1 Like

Awesome! I’m glad it worked for you.