Search code examples
javascriptjquery-select2angularjs-select2

filling a Select2 select box with an array populated by an ajax query


I'd like to use Select2 for a select box, populated by an ajay query to an api with a single call to the api. There is no need to query the api again after every keystroke.

I tried to implement it using this thread: How to pre-load an array via ajax and use it for select2? but I still cannot get it to work after hours -.-

My code:

<script type="text/javascript">
        $(document).ready(function() {
            var linkableSystems = [];
            $.ajax({
                url: 'ulrHere'
            }).done(function(data) {
                linkableSystems = data.results;
                console.log(linkableSystems);
                $('#SelectLinkedSystemToAdd').select2('enable', true);
            });
            $('#SelectLinkedSystemToAdd').select2({
                dataType: 'json',
                data: function () { return { results: linkableSystems }; }
            },
                console.log(linkableSystems)
            ).select2('enable', false);
        });


    </script>
<select id="SelectLinkedSystemToAdd" class="form-control"></select>

The api returns:

{
    "results": [
        {
            "text": "demo CLIENT 1",
            "id": 1
        },
        {
            "text": "demo CLIENT 2",
            "id": 2
        }
    ]
}

I tried to populate the select box with the select2 ajax call and it works. But I cannot get it to work so that it only does 1 single api call. According to the console, linkableSystems is empty at first:

[]
​length: 0

and then filled by the ajax request:

(2) […]
​0: Object { text: "demo CLIENT 1", id: 1 }
​1: Object { text: "demo CLIENT 2", id: 2 }

Sadly, these changes are not picked up by Select2 as suggested in the thread I linked above.

Can anyone please help me with this? If you need any more information, please ask!

Thanks!


Solution

  • Keep in mind that these requests are asynchronous.

    $.ajax({
      url: 'ulrHere'
    }).done(function(data) {
      $('#SelectLinkedSystemToAdd').select2({data: data.results});
    });
    

    Should do the trick, since you update the select2 when the data actually is available. In case you initiliazed the select2 before it's a bit iffy sometimes. You might have to do $('#SelectLinkedSystemToAdd').select2('destroy')and reinit the select with the data again.