Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Select2 load JSON resultset via AJAX and search locally

Until now I've been using Select2's normal AJAX method of searching and filtering data serverside, but now I have a usecase where I want to retrieve all the results via AJAX when the select is opened and then use those results (now stored locally) to search and filter.

I've trawled the web looking for examples of how to do this and all i've found is lots of people saying the Query method should be used rather than the AJAX helper. Unfortunately I haven't found any examples.

So far all I've managed is the basic:

$('#parent').select2({
  placeholder: "Select Parent",
  minimumInputLength: 0,
  allowClear: true,
  query: function (query) {
      //console.log(query);
      query.callback(data);
  }
});

data = {
 more: false,
 results: [
    { id: "CA", text: "California" },
    { id: "AL", text: "Alabama" }
 ]
}

Data is being passed to the select but query filtering is not implemented.

I'm struggling to understand the select2 documentation and would appreciate any assistance or links to examples.

like image 255
Tim Avatar asked Oct 20 '25 05:10

Tim


1 Answers

Try the following - pre-load json data into local variable and when ready bind this to select2 object

<script>
function format(item) { return item.text; }
var jresults;
$(document).ready(function() {
    $.getJSON("http://yoururl.com/api/select_something.json").done(
        function( data ) {
            $.jresults = data;
            $("#parent").select2(
                {formatResult: format,
                 formatSelection: format,
                 data: $.jresults }
            );
        }
    )
});
</script>
like image 149
Nicholas Avatar answered Oct 22 '25 19:10

Nicholas