json response from php to select2 not rendering

902 views Asked by At

I am trying to use select2 pulling data using AJAX from PHP back end. I could not figure out the documentation as much as I would like to. I think I probably missed some taken for granted stuffs.
I started like this:

HTML

<select id="select_proj" style="width:10em">
  <option value="" selected="selected">Search</option>
</select>

js

$('select').select2();
$("#select_proj").select2({
    ajax : {
        url : '../app/select_prj.php',
        dataType : 'json',
        delay : 250,
        data : function (term, page) {
            return {
                select_proj: term, // search term
                page: 10
            };
        },
        processResults: function (data, page) {
            return {
                results: data.items
            };
        },
        cache: true
    },
    escapeMarkup : function (markup) { return markup; }, // let our custom formatter work
    minimumInputLength : 1,
});

In PHP

json object is returned from PHP

echo json_encode($result_data);

and the data looks like

[{
    "PROJ_ID" : 10039,
    "0" : 10039
},{
    "PROJ_ID" : 10042,
    "0":10042
}] 

However nothing is happening in the select box except a message "No results found".
What am I missing out?

1

There are 1 answers

1
Sebastian Hens On BEST ANSWER

Your response have to look like this:

[
    { id: 0, text: 'enhancement' },
    { id: 1, text: 'bug' }, 
    { id: 2, text: 'duplicate' },
    { id: 3, text: 'invalid' }, 
    { id: 4, text: 'wontfix' }
]
  • "id" will be the option value
  • "text" will be the option label

and you have to remove the ".items" from "data.items" because you don't have the key "items" in your response.