Loading remote data only once with Select2

Viewed 15695

As the title suggests I would like to load remote data once only. I thought about loading a data with independent ajax call and set it "locally" at the control but wonder if there is more "built in" way to do so...

4 Answers

This is for Select2 v4.0.3:

I had this same question and got around it by triggering an AJAX call and using the data returned as the initialized data array.

// I used an onClick event to fire the AJAX, but this can be attached to any event.
// Ensure ajax call is done *ONCE* with the "one" method.
$('#mySelect').one('click', function(e) {
    // Text to let user know data is being loaded for long requests.
    $('#mySelect option:eq(0)').text('Data is being loaded...');
    $.ajax({
        type: 'POST',
        url: '/RetrieveDropdownOptions',
        data: {}, // Any data that is needed to pass to the controller
        dataType: 'json',
        success: function(returnedData) {
            // Clear the notification text of the option.
            $('#mySelect option:eq(0)').text('');
            // Initialize the Select2 with the data returned from the AJAX.
            $('#mySelect').select2({ data: returnedData });
            // Open the Select2.
            $('#mySelect').select2('open');
        }
    });
    // Blur the select to register the text change of the option.
    $(this).blur();
});

This worked well for what I had in mind. Hope this helps people searching with the same question.

In my condition, it is working perfectly with the given code

$('#itemid').select2({
    cacheDataSource: [],
    closeOnSelect: true,
    minimumInputLength: 3,
    placeholder: "Search Barcode / Name",
    query: function(query) {
        // console.log(query);
        self = this;
        var key = query.term;
        var cachedData = self.cacheDataSource[key];
        if(cachedData) {
            query.callback({results: cachedData});
            return;
        } else {
            $.ajax({
                url: "./includes/getItemSelect2.php",
                data: { value : query.term },
                dataType: 'json',
                type: 'POST',
                success: function(data) {
                    self.cacheDataSource[key] = data;
                    query.callback({results: data});
                }
            });
        }
    },
});

And my data return from the ajax is in this form

<?php
$arr = [
    ["id" => 1, "text" => "Testing"],
    ["id" => 2, "text" => "test2"],
    ["id" => 3, "text" => "test3"],
    ["id" => 4, "text" => "test4"],
    ["id" => 5, "text" => "test5"]
];
echo json_encode($arr);
exit();
?>
Related