javascriptjquery-select2

Fetching and caching the result in Select2


My application uses select2 to show list of names which is retrieved through Ajax call. It uses select2 ajax functionalities.

But the problem is that select2 fetches items whenever i type on the select2 input. I dont want to fetch every time user type. I want to fetch items in the initial loading of select2 and then uses same data even if they typing in the select2 input.

How can i achieve this?

PS: I have seen cache flag in Ajax, but i think it does caching the result based on the URL. It does not stop fetching of data when user type on the select2 input.


Solution

  • Select2 load data using ajax with caching in-place.

    $("#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; } 
    });