Select2 - Pass back additional data via ajax call Select2 - Pass back additional data via ajax call ajax ajax

Select2 - Pass back additional data via ajax call


Can't comment for now (low reputation).. so... answering to slick:

Including additional data (v4.0):

processResults: function (data) {    data = data.map(function (item) {        return {            id: item.id_field,            text: item.text_field,            otherfield: item.otherfield        };    });    return { results: data };}

Reading the data:

var data=$('#contact_id').select2('data')[0];console.log(data.otherfield);


Can't remember what I was doing wrong, but with processResults(data), data contains the full response. In my implementation below, I access this info when an item is selected:

$('#select2-box').select2({    placeholder: 'Search Existing Contacts',    ajax: {        url: '/contacts/typeahead',        dataType: 'json',        delay: 250,        data: function(params){            return {                q: params.term,                type: '',                suggestions: 1            };        },        processResults: function(data, params){            //Send the data back            return {                results: data            };        }    },    minimumInputLength: 2}).on('select2:select', function(event) {    // This is how I got ahold of the data    var contact = event.params.data;    // contact.suggestions ...    // contact.organization_id ...});// Data I was returning[    {        "id":36167, // ID USED IN SELECT2        "avatar":null,        "organization_id":28037,        "text":"John Cena - WWE", // TEXT SHOWN IN SELECT2        "suggestions":[            {                "id":28037,                "text":"WWE",                "avatar":null            },            {                "id":21509,                "text":"Kurt Angle",                "avatar":null            },            {                "id":126,                "text":"Mark Calaway",                "avatar":null            },            {                "id":129,                "text":"Ricky Steamboat",                "avatar":null            },            {                "id":131,                "text":"Brock Lesnar",                "avatar":null            }        ]    }]