@coder72 you don't have to put that data at loading.
That's the idea of using ajax...to fetch only those countries that match your selection.
Your second snippet is almost there, although you need to pass the 'query' typed by the user to your API endpoint.
In your example, you should end up with something like this:
$("#countries").select2({
ajax: {
url:"http://ims.rarait.com/api/filterCountries",
dataType: 'json',
data: function (params) {
return {
q: params.term, // search term
};
},
results: function (data) {
return {
results: data.countries.forEach(function (country) {
return {
text: country.name,
id: country.id
}
})
}
}
}
})
I leave you a codepen that I've made using a public REST API that returns Countries based on a search term (it has a weird way of returning the data, but it works as an example) so you can check it out working:
https://codepen.io/mmoreyra/pen/wvWodKp
Hope this works for you!