Select 2 ajax call not populating with results

Just downloaded a select2 files from github, the latest release 4.0.3, and i want to populate the options based on what i'm typing (ajax request)

heres the code

$('#usernetwork').select2({
    ajax: {
        url: 'someurl.php',
        dataType: 'json',
        delay: 250,
        data: function (params) {
          return {
            q: params.term, // search term
            page: params.page
          };
        },
        processResults: function (data, page) {

          return data.items;
        },
        cache: false
    },
    minimumInputLength: 1
});

the url (someurl.php) shows this json result

[{"id":"1","text":"ClickWeb"},{"id":"2","text":"ClickWeb 1"},{"id":"3","text":"ClickWeb 2"},{"id":"4","text":"ClickWeb 3"}]

and finally the select field is this

<select name="usernetwork" id="usernetwork" class="form-control">
</select>

this is the very first time i try this for now im getting nothing as query (for test purposes)

The results are not showing up, and i have no idea on how to fix this, any tips?

Upvotes: 1

Views: 2079

Answers (1)

R.K.Saini
R.K.Saini

Reputation: 2708

Try my answer the only thing you need to change is your return statement inside processResults callback like this

return {
          results: data

       };

Here is full code :

         $('#usernetwork').select2({
                    ajax: {
                        url: 'someurl.php',
                        dataType: 'json',
                        delay: 250,
                        data: function (params) {
                            return {
                                q: params.term, // search term
                                page: params.page
                            };
                        },
                        processResults: function (data, page) {

                             return {
                                results: data

                              };
                        },
                        cache: false
                    },
                    minimumInputLength: 1
                });

Upvotes: 1

Related Questions