Johann Echavarria Johann Echavarria - 1 year ago 175
Javascript Question

JSON format for jquery-select2 multi with ajax

I'm thinking in moving from Chosen to Select2 because Select2 has native methods for ajax. Ajax is critical because usualy you have to load a lot of data.

I executed sucessfully the example with the JSON of

I did a JSON file to test the ajax, but it didn't works.

I don't know how the JSON should be. It seems that there is no detailed documentation:

I tried unsucessfully several JSON formats, so I tried to copy a JSON format similar to api.rottentomatoes but it doesn't works.

I may be missing something stupid.

function MultiAjaxAutoComplete(element, url) {
placeholder: "Search for a movie",
minimumInputLength: 1,
multiple: true,
ajax: {
url: url,
dataType: 'jsonp',
data: function(term, page) {

return {
q: term,
page_limit: 10,
apikey: "z4vbb4bjmgsb7dy33kvux3ea" //my own apikey
results: function(data, page) {
return {
results: data.movies
formatResult: formatResult,
formatSelection: formatSelection,
/*initSelection: function(element, callback) {
var data = [];
$(element.val().split(",")).each(function(i) {
var item = this.split(':');
id: item[0],
title: item[1]

function formatResult(node) {
return '<div>' + + '</div>';

function formatSelection(node) {

/*MultiAjaxAutoComplete('#e6', '');*/

MultiAjaxAutoComplete('#e6', '');

$('#save').click(function() {

I did this jsfiddle:

Answer Source

If you switched to JSON make sure you switch dataType to JSON from JSONP.

The format is specified here:

The JSON should look like this:

{results: [choice1, choice2, ...], more: true/false }

Basically the only required attribute in the choice is the id. if the option contains other child options (such as in case of optgroup-like choices) then those are specified inside the children attribute.

The default choice and selection renderer expect a text attribute in every choice - that's what is used to render the choice.

so a complete example of a US state using default renderer might look like this:

    "results": [
            "id": "CA",
            "text": "California"
            "id": "CO",
            "text": "Colarado"
    "more": false

Hope this gets you started.

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download