1
votes

I am having an issue with assigning large set of data to jQuery select2 dropdown. I have an Ajax controller call which returns customer data (id & name) and assign it to a select2 dropdown box inside success call of Ajax. The problem is I have around 77k customer records and because of that select2 is not handling it well and browser hangs after few seconds.

As a solution I came across pagination in select2 and tried quite a few examples but none of them are working in my scenario. I am loading all customer data at once because I don't want to make frequent queries to search for customer record.

I have a javascript function which gets the data from controller (Ruby) and assign it to select dropdown using select2.

function updateCustomerList(teamId, customerSelectInput) {
    if(teamId !== undefined) {
        $.ajax({
            dataType: "json",
            url: "/team/customers",
            data: {team_id: teamId},
            success: function(data) {
                $(customerSelectInput).select2({
                    createSearchChoice: createSearchChoiceFunction,
                    placeholder: "Search for customer"],
                    data: data
                });
            },
            error: function(jqXHR, textStatus, errorThrown) {
                displayError(jqXHR.responseText)
            }
        });
    }

    var createSearchChoiceFunction = function(term, data) {
        if ( $(data).filter( function() {
                return this.text.localeCompare(term)===0;
            }).length===0) {
            return {id:term, text:term};
        }
    }
}

FYI Team controller method "customers" is just making a query to customer collection and gets all customer by team id and return the result as json object.

Any kind of help/guidance would be appreciated!

1

1 Answers

0
votes

I have around 77k customer records and because of that select2 is not handling it well and browser hangs after few seconds.

Well, that happened because all data is loading in memory, you will see that all your RAM go off. In the DOM, many <options> are created, and chrome it will be happy eating all your memory.

I think you can get better results with Algolia API and Autocomplete.js which is a JavaScript library that adds a fast and fully-featured auto-completion menu to your search box displaying results "as you type".

https://github.com/algolia/autocomplete.js