I already read this , this , this, and according to the documentation, the most important one here , but none of them work for me. I am trying to use AJAX select2. I am trying to create a generic "select" element.
So, for all elements that have the data-select2-json attribute, I apply select2 with the ajax url that is in the value of data-select2-json .
$('[data-select2-json!=""][data-select2-json]').each(function() { var url = $(this).attr('data-select2-json'); var pg_size = $(this).attr('data-select2-page-size') | 30; $(this).select2({ language: language_code, tokenSeparators: [',', ' '], ajax: { url: url, dataType: 'json', delay: 300, data: function (params) { return { q: params.term,
It works well!

JSON sends a server, which is always formatted as follows:
{"items": [{"item": "Fran\u00e7ais", "id": 1}, {"item": "Finlandais", "id": 5}, {"item": "Chinois simplifi\u00e9", "id": 15} ], "total": 3}
This is very close to the AJAX sample that you can find in the documentation . My problem is AJAX initatilize: I want to either add values to the HTML:
<select multiple="multiple" class="form-control" data-select2-json="/fr/chez-moi/tags/langues" multiple="multiple" name="known_languages"> <option value="1" selected="selected">Français</option> <option value="2" selected="selected">Chinois simplifié</option> </select>
and then initialize with select2 (= code $(this).select2({.. above), but this does not work and gives me empty values:

NB: the solution given by Kevin Brown does not work and gives me exactly the same result.
Another solution is to ask AJAX the URL with the parameter "
&init=1 " (or something like that) so that the server sends the results with the added parameters, such as
checked: true for each value, and I will call
select2 with these values.
In the documentation on how to pre-populate select2 , nothing is visible. How can I do it?
Here are my other features:
function item_or_text(obj) { if (typeof(obj.item)!='undefined') { return (obj.item.length ? obj.item : obj.text); } return obj.text; } function formatRepo(data) { if (data.loading) return data.text; var markup = item_or_text(data); console.log('formatRepo', data, markup); return markup; } function formatRepoSelection(item) { var retour = item_or_text(item); console.log('formatRepoSelection', item, item.item, retour); return retour; }