Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Select2 not getting data via AJAX

I have the following code which should be getting data via AJAX using Select2

$('#Organisation').select2({
    ajax: {
        url: AppURL + 'Organisations/Manage/SearchByName/',
        dataType: 'json',
        quietMillis: 100,
        data: function (term) {
            return {
                term: term
            };
        },
        results: function (data) {
            return {
                results: data
            };
        }
    }
});

If I look at the request using Web Inspector when searching 'O' I get:

[{"label":"Organisation 1","ID":2},{"label":"Organisation 2","ID":1}]

Any ideas what I'm doing wrong? I'd presume something incorrect in the results function.

The error I get is: Uncaught TypeError: Cannot call method 'toUpperCase' of undefined

like image 689
Cameron Avatar asked Apr 19 '13 09:04

Cameron


2 Answers

Other than above solution you can do one thing, instead of returning following json

[{"label":"Organisation 1","ID":2},{"label":"Organisation 2","ID":1}]

return this

[{"text":"Organisation 1","id":2},{"text":"Organisation 2","id":1}]

faced the same problem and figured this out after looking at few solutions proposed by other.

like image 78
Afnan Bashir Avatar answered Oct 18 '22 22:10

Afnan Bashir


Try

$('#Organisation').select2({
    ajax: {
        url: 'data.json',
        dataType: 'json',
        quietMillis: 100,
        data: function (term) {
            return {
                term: term
            };
        },
        results: function (data) {
          var results = [];
          $.each(data, function(index, item){
            results.push({
              id: item.ID,
              text: item.label
            });
          });
          return {
              results: results
          };
        }
    }
});

Demo: Plunker

like image 35
Arun P Johny Avatar answered Oct 18 '22 20:10

Arun P Johny