Skip to content

Instantly share code, notes, and snippets.

@berkSahin
Forked from techniq/select2_ajax.js
Created September 24, 2018 16:31
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save berkSahin/b119c6e7bc36bac8c03579685d63d416 to your computer and use it in GitHub Desktop.
Save berkSahin/b119c6e7bc36bac8c03579685d63d416 to your computer and use it in GitHub Desktop.
Select2 ajax example with custom query call to append data to the request. Note: Providing ajax settings is not needed (and not used) when query is provided. Left here as a full example.
$("[data-provide='select2']").each(function () {
var $element = $(this);
$element.select2({
placeholder: $element.data("placeholder"),
minimumInputLength: 0,
allowClear: true,
initSelection: function (element, callback) {
callback({
id: $(element).val(),
text: $(element).data('selected-text')
});
},
query: function (query) {
var url = $element.data("url");
var contextData = {};
var contexts = $element.data("context").split(",");
_.map(contexts, function (c) {
var name = c.trim();
var value = $("[name='" + name + "']").val();
if (value) {
contextData[name] = value;
}
});
var data = {
query: query.term,
page: query.page,
pageLimit: 25
};
$.extend(data, contextData);
$.post(url, data, function (results) {
query.callback(results);
});
},
ajax: {
url: $element.data("url"),
type: "POST",
quietMillis: 100,
data: function (term, page) {
return {
query: term,
page: page,
pageLimit: 25
};
},
results: function (data, page) {
return data;
}
}
});
});
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment