Reputation: 4893
I'm trying to get Select2 working with Rails. I have the API endpoint working but I get a TypeError: data is undefined
message in my console, so the select fields aren't being populated.
My code looks like this:
$(document).ready(function() {
return $('#form_emails').select2({
placeholder: 'User list',
minimumInputLength: 3,
ajax: {
url: '/api/s/users',
dataType: 'json',
quietMillis: 250,
data: function(term) {
return { q: term };
},
results: function(data) {
var results;
results = [];
$.each(data, function(idx, item) {
results.push({
'id': item.id,
'text': item.first_name + ' ' + item.last_name
});
});
return { results: results };
}
}
});
});
Any idea why I might be getting the aforementioned error? Thanks in advance!
Upvotes: 1
Views: 1303
Reputation: 17647
According to Select2 documentation the function where you can transform data from Ajax request is named processResults
, not results
.
See: https://select2.org/data-sources/ajax#transforming-response-data
So the correct code should be:
$(document).ready(function() {
return $('#form_emails').select2({
placeholder: 'User list',
minimumInputLength: 3,
ajax: {
url: '/api/s/users',
dataType: 'json',
quietMillis: 250,
data: function(term) {
return { q: term };
},
processResults: function(data) {
var results;
results = [];
$.each(data, function(idx, item) {
results.push({
'id': item.id,
'text': item.first_name + ' ' + item.last_name
});
});
return { results: results };
}
}
});
});
Upvotes: 1