jQuery select2 AJAX not working
Asked Answered
W

2

12

I'm using the jQuery select2 plugin and trying to get the AJAX to work with my ext data which is obviously not working and I'm just wondering if someone can point out what I'm doing wrong or missing something?

NOTE This is only for select v3.5.2

my js:

$('#cliselect').select2({
    ajax: {
        dataType: "json",
        url: "clientprojectpopulate.php",
        results: function (data) {
            return {results: data};
        }
    }
});

html:

<select id="cliselect" name="cliselect" style="width: 100%;" /></select>

my JSON returns (which I believe is valid):

[{"id":"62","text":"Alberta Innovates Health Solutions"},{"id":"4","text":"Alterna Savins & Credit Union"},{"id":"63","text":"BC Patient Safety & Quality Council"}]
Willpower answered 25/2, 2014 at 18:12 Comment(0)
W
14

Figured out its because i was using <select>

It has to be an <input> for the ajax data to load...

<input type="hidden" id="cliselect" name="cliselect" style="width: 100%;" />
Willpower answered 25/2, 2014 at 19:42 Comment(2)
On Select2 4.0 is the other way round. It didn't work because it was an input instead of a select.Siracusa
thanks for the help I had an input, changed it to a select and worked like a charm!Missal
E
20

The Select2 control is updated to version 4.0. Now input elements are not working any longer and there should be select elements in place of them.

The results have also been changed to

processResults: function (data) {
    return {
      results: data
    };  
}

Inside the processResults function you can use them like this:

processResults: function (data) {
    var results = [];
    $.each(data, function (index, account) {
        results.push({
            id: account.AccountID,
            text: account.AccountName
        });
    });

    return {
        results: results
    };
}
Eatton answered 19/10, 2015 at 9:18 Comment(0)
W
14

Figured out its because i was using <select>

It has to be an <input> for the ajax data to load...

<input type="hidden" id="cliselect" name="cliselect" style="width: 100%;" />
Willpower answered 25/2, 2014 at 19:42 Comment(2)
On Select2 4.0 is the other way round. It didn't work because it was an input instead of a select.Siracusa
thanks for the help I had an input, changed it to a select and worked like a charm!Missal

© 2022 - 2024 — McMap. All rights reserved.