Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Select2 errors - no response

I'm using Select2 to provide dynamic select functionality on my page.

Here is the code:-

$("#Spon_Index").select2({
    placeholder: "Type to select a sponsor",
    minimumInputLength: 3,
    multiple: false,
    width: 400,
    ajax: {
        url: "../control/autocomplete_sponsor.aspx",
        data: function(term) {
            return term;
        },
        results: function(data, page) {
            alert(results);
            return {
                results: data
            }
        },
        formatResult: function(data) {
            return data.text;
        },
        formatSelection: function(data) {
            return data.id;
        },
        escapeMarkup: function(m) {
            return m;
        }
    }
});

Using Fiddler, I can see that I'm getting the correct return from autocomplete_sponsor.aspx, example:-

[{"id":"12","text":"Smiths"},{"id":"118","text":"Dr Smiths"}]

However, nothing is happening with the control at all. It either hangs on 'Searching', or nothing...I've checked the developer tools and there is an error:-

Uncaught TypeError: Cannot read property 'slice' of undefined

I've looked at some other solutions on SO, and tried various refactorings of my code to get this to work but I've now officially run out of ideas....hoping it's something really simple I've missed out.

like image 291
Mat Richardson Avatar asked May 27 '15 14:05

Mat Richardson


1 Answers

Select2 just seems to need a Javascript object instead of a JSON string. The below code is for select2 v4.0.3, so results was replaced by processResults.

$("#Spon_Index").select2({
    placeholder: "Type to select a sponsor",
    minimumInputLength: 3,
    multiple: false,
    width: 400,
    ajax: {
        url: "../control/autocomplete_sponsor.aspx",
        data: function(term) {
            return term;
        },
        processResults: function(data, page) {
            return { results: JSON.parse(data) };
        },
    }
});
like image 56
Kevin Dimey Avatar answered Sep 22 '22 00:09

Kevin Dimey