How to use Select2 with JSON via Ajax request?
for select2 v4.0.0 slightly different
$(".itemSearch").select2({
tags: true,
multiple: true,
tokenSeparators: [',', ' '],
minimumInputLength: 2,
minimumResultsForSearch: 10,
ajax: {
url: URL,
dataType: "json",
type: "GET",
data: function (params) {
var queryParameters = {
term: params.term
}
return queryParameters;
},
processResults: function (data) {
return {
results: $.map(data, function (item) {
return {
text: item.tag_value,
id: item.tag_id
}
})
};
}
}
});
Here you have an example
$("#profiles-thread").select2({
minimumInputLength: 2,
tags: [],
ajax: {
url: URL,
dataType: 'json',
type: "GET",
quietMillis: 50,
data: function (term) {
return {
term: term
};
},
results: function (data) {
return {
results: $.map(data, function (item) {
return {
text: item.completeName,
slug: item.slug,
id: item.id
}
})
};
}
}
});
It's quite easy