jquery-select2jquery-select2-3

Loading pages of ajax select2 data in the background


I have a AJAX select2 drop-down menu set up to do infinite paging. What'd I'd like to do is go ahead and load the first page of results in the background so that as soon as the user clicks the drop-down, they have a set of options immediately, instead of waiting on the initial AJAX call.

When I search Google for how to do this, I only see results about trying to set an initial selection, which isn't what I want to do. I just want to pre-load the first page of results from my endpoint so the user sees data immediately instead on waiting for the AJAX call to return. Is this even possible?

My select2 setup code is below:

$(".my-class-identifier").select2({

        ajax: {
            cache: true,
            dataType: "json",
            delay: 500, 
            data: function(params, page) {

                return {
                    name: params,
                    otherParams: $(this).data("other-params")
                    page: page                      
                };

            },
            results: function(data, page) {

                return {
                    /* The server returns no data after all the pages have been returned. */
                    more: data && data.length > 0,
                    results: data
                };

            },
            type: "GET",
            url: function() {
                if ($(this).data("url")) {
                    return $(this).data("url");
                } else {
                    return DEFAULT_ENDPOINT;
                }
            }
        },
        allowClear: true,
        minimumInputLength: 0,
        placeholder: "Search for some data..."          
    });

Solution

  • So what you are looking for is to initialize your select2. Select2 has an initialize option to load your values, it would look something like this:

        initSelection: function(element, callback){
            callback([
               {id:1,text:'one'},
               {id:2,text:'two'},
            ]);
        }
    

    Be sure to add this outside your ajax call, but inside your select2.

    An example here in JSFiddle