Can Select2 be connected to a remote data source?
Select2 supports connecting to a remote data source using the ajax
option.
How can I set the initially selected options when using AJAX?
You can refer to the following Stack Overflow answer if you want to set the initial value for AJAX requests: Select2 4.0.0 initial value with AJAX
What should the results returned to Select2 look like?
{% include options/not-written.html %}
Is there a way to modify the response before passing it back to Select2?
You can use the ajax.processResults
option to modify the data returned from the server before passing it to Select2.
{% highlight js linenos %}
$('select').select2({
ajax: {
url: '/example/api',
processResults: function (data) {
return {
results: data.items
};
}
}
});
{% endhighlight %}
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.
{% highlight js linenos %}
$('select').select2({
ajax: {
url: '/example/api',
delay: 250
}
});
{% endhighlight %}
This will tell Select2 to wait 250 milliseconds before sending the request out to your API.
I want to add more query parameters to the request, where can this be done?
By default, Select2 will send the query term as well as the pagination data as query parameters in requests. You can override the data that is sent to your API, or change any of the query paramters, by overriding the ajax.data
option.
{% highlight js linenos %}
$('select').select2({
ajax: {
data: function (params) {
var query = {
search: params.term,
page: params.page
}
// Query paramters will be ?search=[term]&page=[page]
return query;
}
}
});
{% endhighlight %}
Can an AJAX plugin other than jQuery.ajax
be used?
Select2 uses the transport method defined in ajax.transport
to send requests to your API. By default, this transport method is jQuery.ajax
but this can be changed.
{% highlight js linenos %}
$('select').select2({
ajax: {
transport: function (params, success, failure) {
var request = new AjaxRequest(params.url, params);
request.on('success', success);
request.on('failure', failure);
}
}
});
{% endhighlight %}