JSON format for jquery-select2 multi with ajax
Asked Answered
N

2

18

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 api.rottentomatoes.com/api/

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:

https://github.com/ivaynberg/select2/issues/920

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) {
    $(element).select2({
        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(':');
                data.push({
                    id: item[0],
                    title: item[1]
                });
            });
            //$(element).val('');
            callback(data);
        }*/
    });
};

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

function formatSelection(node) {
    return node.id;
};


/*MultiAjaxAutoComplete('#e6', 'http://api.rottentomatoes.com/api/public/v1.0/movies.json');*/

MultiAjaxAutoComplete('#e6', 'https://raw.github.com/katio/Quick-i18n/master/test.json');

$('#save').click(function() {
    alert($('#e6').val());
});

I did this jsfiddle:

http://jsfiddle.net/Katio/H9RZm/4/

Nettles answered 16/5, 2013 at 22:27 Comment(1)
Good question mate, select2 ajax section docs made no sense to me, I am sure that many will have this question.Aldershot
D
35

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

The format is specified here: http://ivaynberg.github.io/select2/#doc-query

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.

Dumfound answered 16/5, 2013 at 22:51 Comment(5)
Thank you and congrats, Select2 is really cool. I was missing the "more" parameter, however I don't see the more parameter in the api.rottentomatoes json. Any way, now it works for me. Thank you for your answer.Nettles
I was going round in circles all the way from Select2 docs to Google and finally here. This answer really saved me. Why don't you have a detailed document for than one-liners? don't say you have one on the docs section, looking at it I felt like reading russian and made no senseAldershot
Apparently, in select2 4.0.0, the default accepted format now is { results: [ {id:'CA', text:'California'}, {id:'CO', text: 'Colarado' ], pagination: { more: false } } (note the pagination attribute)Glut
The format is no longer available at that URL. It seems the new documentation format these days is very sparse documentation. Then the people who need the documentation are expected to write (what they don't know) it and submit PRs, while those that already know it, don't know the documentation is not there and so have no need to find it missing and submit PRs. The state of front end development is becoming more of a dirty mess every time I look at it. Dipping into front end takes longer and longer on each job.Burgonet
@hg8 the fiddle doesn't return a result. Could you please check?Suiter
H
0

Official documentation for required JSON format: ref. https://select2.org/data-sources/formats

{
  "results": [
    {
      "id": 1,
      "text": "Option 1"
    },
    {
      "id": 2,
      "text": "Option 2"
    }
  ],
  "pagination": {
    "more": true
  }
}
Hamid answered 6/2, 2018 at 11:50 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.