Select2 not getting data via AJAX
Asked Answered
I

2

13

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

Indrawn answered 19/4, 2013 at 9:52 Comment(1)
will you be able to change the json response structureBabylon
B
35

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

Babylon answered 19/4, 2013 at 10:24 Comment(2)
This is very useful sample. my problem solved after 4 hours searching. thanksSaturation
thank you so much! was very useful for select2.min version 3.5.4 :)Gabby
P
5

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.

Petulah answered 1/10, 2014 at 20:59 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.