I'm needing to download names of cities in a comboBox Select2 via ajax, but so far it has not worked. many examples in internet search, but not understand them too.
$(document).ready(function() {
var url = "http://localhost:8000/api/city?";
$("#city").select2({
minimumInputLength: 1,
ajax: {
url: url,
dataType: 'json',
type: "GET",
delay: 500,
data: function (term) {
return {
city: term
};
},
results: function (data) {
console.log(data);
return {
results: $.map(data, function (item) {
return {
text: item.text,
id: item.id
}
})
};
}
}
});
});
y este es el código json que devuelve mi servidor con la consulta realizada:
[{ "id": 1, "text": "Capital, Córdoba, Argentina" }]
Dice "Searching...." y luego "No results found"
Really, Thanks!
First of all if you are using Select2 version 4+, make sure you initialize select2() on a <select>
element or many of his feature like AJAX will be turned off.
Select2 will need a formated answer from your server at : http://localhost:8000/api/city?
Response returned by your server should look like this:
[
{id:1,text:'city1'},
{id:2,text:'city2'},
]
The options: minimumInputLength = 0
, will make it load the whole list on click minimumResultsForSearch
, control how many results you need to display the search box into select2 list.
ajax{data: function(param)}
is the function called to format the user data into something your server will understand, what you return here is send to your {ajax:url}
ajax{processResults: function (data, status)}
, this is called when you ajax got a successful response from your server , data
will be the response from your server this is the last chance you have to make sure that data
is formated like select2 need , see top of this post. What you return here is send to select2.
Hope it help!