1

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?

2
  • "No results found" where ? Commented Jun 9, 2015 at 13:38
  • Inside select component just below where user types the entries Commented Jun 9, 2015 at 13:43

1 Answer 1

2

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.

Sign up to request clarification or add additional context in comments.

1 Comment

Thanks so much. Was not able to find this in doc.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.