Download remote data only once with Select2

As the name implies, I would like to download deleted data only once. I thought about loading data with an independent ajax call and set it “locally” in the control, but I wonder if there is a more “built-in” way to do this ...

+8
javascript jquery-plugins web
source share
3 answers

solution can be found here:

https://github.com/ivaynberg/select2/issues/110

$("#selIUT").select2({ cacheDataSource: [], placeholder: "Please enter the name", query: function(query) { self = this; var key = query.term; var cachedData = self.cacheDataSource[key]; if(cachedData) { query.callback({results: cachedData.result}); return; } else { $.ajax({ url: '/ajax/suggest/', data: { q : query.term }, dataType: 'json', type: 'GET', success: function(data) { self.cacheDataSource[key] = data; query.callback({results: data.result}); } }) } }, width: '250px', formatResult: formatResult, formatSelection: formatSelection, dropdownCssClass: "bigdrop", escapeMarkup: function (m) { return m; } }); 

Edit:

I could misinterpret your question. if you want to load all the data once, then use Select2, there are no built-in functions for this.

Your suggestion to make one request and then use the data stored in Select2 will be a way.

+5
source share

To download data once:

Assumptions:

  • You have a REST API endpoint in / services that serves an array of JSON objects

  • The array contains objects that have at least the attribute "name" and "id". Example:

     [{"id": 0, "name": "Foo"}, {"id": 1, "name": "Bar"}] 
  • You want to save this array as a global 'services_raw'

Firstly, our function for loading data and creating a global "services_raw" (AKA "window.services_raw"):

  fetchFromAPI = function() { console.log("fetchFromAPI called"); var jqxhr = $.ajax( { dataType:'json', type: 'GET', url: "/services", success: function(data, textStatus, jqXHR) { services_raw = data; console.log("rosetta.fn.fetchServicesFromAPI SUCCESS"); rosetta.fn.refreshServicesSelect(); }, error: function(jqXHR, textStatus, errorThrown) { console.log("Error inside rosetta.fn.fetchServicesFromAPI", errorThrown, textStatus, jqXHR); setTimeout(rosetta.fn.fetchServicesFromAPI(), 3000); // retry in 3 seconds } } ) .done(function () { console.log("success"); console.log(jqxhr); }) .fail(function () { console.log("error"); }) .always(function () { console.log("complete"); }); // Perform other work here ... // Set another completion function for the request above jqxhr.always(function () { console.log("second complete"); }); }; 

Secondly, our selection code is Select2, which converts our data to a format that Select2 can select:

 refreshServicesSelect = function () { // ref: http://jsfiddle.net/RVnfn/2/ // ref2: http://jsfiddle.net/RVnfn/101/ # mine // ref3: http://jsfiddle.net/RVnfn/102/ # also mine console.log('refreshServicesSelect called'); $("#add-service-select-service").select2({ // allowClear: true data: function() { var arr = []; // container for the results we're returning to Select2 for display for (var idx in services_raw) { var item = services_raw[idx]; arr.push({ id: item.id, text: item.name, _raw: item // for convenience }); } return {results: arr}; } }); }; 

Here, what the Select2 element in HTML should look like before your call above:

 <input id="add-service-select-service" type="hidden" style="width:100%"> 

To use all of this, call (in JS):

 window.fetchFromAPI(); window.refreshServicesSelect(); 

Finally, here is JSFiddle where you can play with a similar thing: http://jsfiddle.net/RVnfn/102/

Basically, in my example above, we just use ajax to populate the equivalent of window.pills in Fiddle.

Hope this helps :)

Answer if you know how to do this using the Select2.ajax function, as this will be a little shorter.

0
source share

This is for Select2 v4.0.3:

I had the same question and get around it by calling an AJAX call and using the data returned as an 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(); }); 

It had a good effect on what I had in mind. Hope this helps people who are looking for the same question.

0
source share

All Articles