I know that the above can be achieved by using quietMillis in the AJAX call, but I am using query to cache the data. And it is here I am not able to delay the AJAX call. Below is the code
$('#AssetType').select2({
cacheDataSource: [],
placeholder: ' ',
quietMillis: 3000,
query: function q(query) {
self = this;
var key = query.term;
var cacheData = self.cacheDataSource[key];
if (cacheData) {
query.callback({
results: $.map(cacheData, function (item) {
return {
text: item.LongDescription,
id: item.AssetTypeID
}
})
});
return;
}
else {
$.ajax({
url: 'http://localhost:52377/api/reference/asset/types/' + key,
dataType: 'json',
type: 'GET',
quietMillis: 3000,
//data: function (query) {
// return { assetType: query.term, };
//},
success: function (data) {
self.cacheDataSource[key] = data;
query.callback({
results: $.map(data, function (item) {
return {
text: item.LongDescription,
id: item.AssetTypeID
}
})
});
},
cache: true
})
}
}
});
Is there any work around to delay the AJAX call so that the AJAX call is not fired for every keystroke?? The reason for using "query" is for caching, which is not achieved just by setting cache to true in the AJAX call.
Select2 will register itself as a jQuery function if you use any of the distribution builds, so you can call . select2() on any jQuery selector where you would like to initialize Select2. // In your Javascript (external . js resource or <script> tag) $(document).
Select2 requires that the id property is used to uniquely identify the options that are displayed in the results list. If you use a property other than id (like pk ) to uniquely identify an option, you need to map your old property to id before passing it to Select2.
By default, Select2 will attach the dropdown to the end of the body and will absolutely position it to appear above or below the selection container. Select2 will display the dropdown above the container if there is not enough space below the container, but there is enough space above it.
The ajax() method in jQuery is used to perform an AJAX request or asynchronous HTTP request. Parameters: The list of possible values are given below: type: It is used to specify the type of request. url: It is used to specify the URL to send the request to.
According to the select2 documentation, you can do this easily.
A request is being triggered on every key stroke, can I delay this?
By default, Select2 will trigger a new AJAX request whenever the user changes their search term. You can set a time limit for debouncing requests using the ajax.delay option.
This will tell Select2 to wait 250 milliseconds before sending the request out to your API.
$('select').select2({
ajax: {
url: '/example/api',
delay: 250
}
});
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With