Where is the error?
My select2 box doesn't show results received from ajax call, it says - The results could not be loaded.
Here is my code:
HTML:
<select class="airportList form-control" name="From_1">
<option disabled selected>Going from</option>
</select>
JS:
$(function() {
$(".airportList").select2({
minimumInputLength: 1,
// data: [{id:'ADL',text:'Adelaide, Australia, ADL'},{id:'MEL',text:'Melbourne, Australia, MEL'}],
ajax: {
type: "GET",
url: "data.php",
dataType: 'json',
delay: 250,
data: function (params) {
return {
q: params.term, // search term
page: params.page
};
},
processResults: function (data) {
return {
results: data
};
}
}
});
});
data.php (that I receive):
[
{id:'ADL',text:'Adelaide, Australia, ADL'},
{id:'MEL',text:'Melbourne, Australia, MEL'}
]
Sorry, here is an updated answer:
processResults: function(data) {
return {
results: $.map(data, function(obj) {
return {
id: obj.id,
text: obj.text
};
})
};
}
This part is where you have the issue I think. See this example: http://jsfiddle.net/jes0wrka/
So the problem in my case was that the format of the JSON from data.php file was INCORRECT!!!:
[
{id:'ADL',text:'Adelaide, Australia, ADL'},
{id:'MEL',text:'Melbourne, Australia, MEL'}
]
The CORRECT JSON should be:
[
{"id":"ADL","text":"Adelaide, Australia, ADL"},
{"id":"MEL","text":"Melbourne, Australia, MEL"}
]