Farzad Pakzad Farzad Pakzad - 1 month ago 32
JSON Question

How to load Json Data into Select2

I have faced a problem using select2 js,
This is my json respond

{"items":[{"name":"majid"}],"total_count":1,"incomplete_results":false}


And this is my javascript code

$(".js-example-data-ajax").select2({
minimumResultsForSearch: Infinity,
width: 250,
//containerCssClass: 'bg-indigo-400',
//dropdownCssClass: 'bg-indigo-400',
//containerCssClass: 'select-lg',
placeholder: "Select a State",
allowClear: true,
//tags: true,
ajax: {
url:'set',//'https://api.github.com/search/repositories',//'set',
dataType: 'json',
delay: 250,
data: function (params) {
//alert(params.page);
return {
q: params.term//, // search term
page: params.page
};
},
processResults: function (data, params) {
// parse the results into the format expected by Select2
// since we are using custom formatting functions we do not need to
// alter the remote JSON data, except to indicate that infinite
// scrolling can be used



params.page = params.page || 1;

return {
results: data.items,
pagination: {
more: (params.page * 30) < data.total_count
}
};
},
cache: true
},
//escapeMarkup: function (markup) { return markup; }, // let our custom formatter work
minimumInputLength: 1,
//templateResult: formatRepo, // omitted for brevity, see the source of this page
//templateSelection: formatRepoSelection // omitted for brevity, see the source of this page
});


I don't know where is my mistake,I have read it's Examples but could not find any solutions,
Thanks very much

Answer

Select 2 accepts a specific JSON object structure i.e. -

var data = [{ id: 0, text: 'enhancement' }, { id: 1, text: 'bug' }, { id: 2, text: 'duplicate' }, { id: 3, text: 'invalid' }, { id: 4, text: 'wontfix' }]; 

In your case "items" key should contain an array of similar objects like [{ id: 1, text: 'bug' }] or you can modify the object before returning, like this -

var data = $.map(yourArrayData, function (obj) {
   obj.id = obj.id || obj.pk; // replace pk with your identifier
   return obj;
});

They have already added below comment in their example code.

processResults: function (data, params) { 
// parse the results into the format expected by Select2

See official docs - https://select2.github.io/examples.html#data-array and read this as well https://select2.github.io/options.html#data.