Search code examples
jquery-select2-4

What data structure is select2 expecting from the server and how should it be handled?


What data structure is select2 (v4.0.3) expecting from the server and how should it be handled?

The question is asked on the official FAQ here, but there is no answer.

I have tried several variations of data structure, but based on this tutorial and this jsFiddle, have assumed what should be returned from the server is a list/array of objects/dicts, eg:

matches = [{"id":"1", "tag":"Python"},{"id":"2", "tag":"Javascript"},{"id":"3", "tag":"MongoDB"}]

I have tried this format with the following Javascript:

$("#my_select").select2({
ajax: {
url: "/tag_search",
dataType: 'json',
delay: 250,
data: function (params) {
return {
q: params.term // search term
};
},
processResults: function (data) {
return {
results: data.matches
};
},
cache: true
},
minimumInputLength: 2,
tags: true,
tokenSeparators: [",", " "],
maximumSelectionLength: 5
});

Firebug results for search on Py:

enter image description here

The search area just displays this:

enter image description here

I am expecting all matches to be showing in the dropdown below the search area.


Solution

  • Solution that worked for me:

    Rename json key (it has to be text), so server response is:

    [{"text": "Python", "id": 1}]
    

    (after coming across this document).

    I also just returned the list itself from the server, rather than making the list a dict value.

    Javascript

    $("#my_select").select2({
    ajax: {
    url: "/tag_search",
    dataType: 'json',
    delay: 250,
    data: function (params) {
    return {
    q: params.term // search term
    };
    },
    processResults: function (data) {
    return {
    results: data
    };
    },
    cache: true
    },
    minimumInputLength: 2,
    tags: true,
    tokenSeparators: [",", " "],
    maximumSelectionLength: 5
    });