Currently using Select2 version 4.0.1
. Implemented ajax
to display results based on user input, but facing an issue where Select2 does not list any results despite receiving the proper response from ajax.
Additionally, the input box loses focus after the ajax response.
This is how Select2 was initialized:
$('#select_tag_element').select2({
closeOnSelect: false,
multiple: true,
placeholder: 'Assign a new tag',
tags: true,
tokenSeparators: [","],
ajax: {
url: "search_url",
dataType: 'json',
type: 'GET',
delay: 250,
data: function(params) {
return {
search: params.term,
page: params.page
};
},
processResults: function(data) {
console.log(data)
return {results: $.map(data, function(item) {
return {id: item.id, text: item.name}
})
};
},
cache: true
}
});
The expected JSON object is retrieved in the Javascript Console.
[Object, Object, Object]
0: Object
id: 239
name: "Tag1"
__proto__: Object
1: Object
id: 255
name: "Tag2"
__proto__: Object
2: Object
id: 256
name: "Tag3"
__proto__: Object
length: 3
__proto__: Array[0]
Any assistance would be highly appreciated. Thank you :)
Update -
Upon debugging, noticed that the result dropdown appears initially but gets removed when
globalEventContext.trigger( "ajaxComplete", [ jqXHR, s ] );
line is executed in jquery.js
.
if ( fireGlobals ) {
globalEventContext.trigger( "ajaxComplete", [ jqXHR, s ] );
// Handle the global AJAX counter
if ( !( --jQuery.active ) ) {
jQuery.event.trigger( "ajaxStop" );
}
}
Is there a way to prevent the result dropdown from closing upon the above trigger?
===============================================================
Update
Solved the issue by realizing I had initialized Select2 on ajax success, causing the result dropdown to hide.