How can Select2 dropdown load results via AJAX
ajax, javascript, jquery, jquery-select2
Solution
Assume u have html
<p>
Hidden field value set in the following format:
<br />
<em>'34:Donnie Darko,54:Heat,27:No Country for Old Men'
</em></p>
<input type='hidden' id="e6" style="width: 500px;" value="34:Donnie Darko,54:Heat,27:No Country for Old Men" />
<br /> <button id="save">Save</button>
<p>
After it's initialised, the hidden field value will change to:<br />
<em>'34,54,27'</em>
<br />
That is the value sent to the server
</p>
and for select2 Ajax
function MultiAjaxAutoComplete(element, url) {
$(element).select2({
placeholder: "Search for a movie",
minimumInputLength: 1,
multiple: true,
id: function(e) { return e.id+":"+e.title; },
ajax: {
url: url,
dataType: 'json',
data: function(term, page) {
return {
q: term,
page_limit: 10,
apikey: "z4vbb4bjmgsb7dy33kvux3ea" //my own apikey
};
},
results: function(data, page) {
alert(data);
return {
results: data.movies
};
}
},
formatResult: formatResult,
formatSelection: formatSelection,
initSelection: function(element, callback) {
var data = [];
$(element.val().split(",")).each(function(i) {
var item = this.split(':');
data.push({
id: item[0],
title: item[1]
});
});
//$(element).val('');
callback(data);
}
});
};
function formatResult(movie) {
return '<div>' + movie.title + '</div>';
};
function formatSelection(data) {
return data.title;
};
MultiAjaxAutoComplete('#e6', 'http://api.rottentomatoes.com/api/public/v1.0/movies.json');
$('#save').click(function() {
alert($('#e6').val());
});
Try doing multiajax call with this ! Refer - http://jsfiddle.net/JpvDt/112/
Problem
I've got a simple select2 box which loads a dropdown menu. But what's the best way to reload the dropdown menu each time the select menu is opened with the results of an AJAX call? The ajax call would return ``` <option value=1> <option value=2> ``` and so on I've look through the AJAX examples on the select2 docs but it looks a little overcomplicated for what I need. TIA