Select2 AJAX json response format

10,915 views
Skip to first unread message

Mac Black

unread,
Feb 10, 2015, 5:43:06 AM2/10/15
to sel...@googlegroups.com
Hi,

Can anyone either help me or point me in the right direction for the documentation on the format of the response back from the server using a remote data AJAX call?

It would appear that my php script is being executed but the Select2 option box never gets populated (the "searching" label does appear & disappear as you type).

Based on the topics on this group, I've changed my php script to be as simple as possible just to get things working:


<?php
header('Content-Type: application/json');
$ret_string="{ results: [ {id:'1', text:'Option 1'}, {id:'2', text:'Option 2'} ],more:false}";
echo json_encode($ret_string);

Even this simple script returns nothing, so I'm not sure what I am doing wrong?

Thanks in advance..

Mac

Mac Black

unread,
Feb 10, 2015, 7:37:34 AM2/10/15
to sel...@googlegroups.com
I forgot to add that I'm using v4.0.0, here is my js code:
$(document).ready(function() {
$('#selectbox-o').select2({
ajax: {
url: "mydata.php",
dataType: 'json',
delay: 250,
data: function (params) {
return {
q: params.term, // search term
page: params.page
};
},
processResults: function (data, page) {
return {
results: data.items
};
}
},
minimumInputLength: 3
});
})
I've not mapped the json data as I believe its in the correct format for the select2 control ("id" & "text" pairs).

Kevin Brown

unread,
Feb 10, 2015, 8:23:57 AM2/10/15
to sel...@googlegroups.com
Hi Mac,


On 02/10/2015 05:43 AM, Mac Black wrote:
Hi,

Can anyone either help me or point me in the right direction for the documentation on the format of the response back from the server using a remote data AJAX call?

We don't have documentation (yet) on the AJAX response format, but the AJAX example lays out the required keys pretty well.



It would appear that my php script is being executed but the Select2 option box never gets populated (the "searching" label does appear & disappear as you type).


The "seaching" label disappears once the results are received and processed.


Based on the topics on this group, I've changed my php script to be as simple as possible just to get things working:


<?php
header('Content-Type: application/json');
$ret_string="{ results: [ {id:'1', text:'Option 1'}, {id:'2', text:'Option 2'} ],more:false}";
echo json_encode($ret_string);


I think this is where your issue currently is. Select2 is expecting the response to come back containing roughly what is contained in `$ret_string`. Right here you are calling `json_encode` on that, which is most likely escaping the string and giving you an invalid response.

You can confirm this by opening the developer tools (F12) and inspecting the returned response (or visiting the url directly). If it doesn't look exactly like what is in `$ret_string`, then that is most likely where your issue is coming from. I would also check out the JavaScript console while you are there, as Select2 should trigger a warning when the response can't be parsed.

Kevin Brown

Mac Black

unread,
Feb 10, 2015, 9:40:48 AM2/10/15
to sel...@googlegroups.com
Kevin, thanks for taking the time to respond, you were right in that in my attempt to simplify the server script, I didn't need to encode the response, and this did escape the string. 

So I removed the json encoding and the output from the script is now 

{"results":[{"id":0,"text":"text name0"}]}

which is a valid json format however I'm still not getting any results. The console for the Select2 gives me 2 errors:

Select2: The AJAX results did not return an array in the `results` key of the response.select2.js:3117 (anonymous function)
Uncaught TypeError: Cannot read property 'slice' of undefined select2.js:3613

I think my example is as simple as it comes, so I've obviously missed something fundamental! 

When you say AJAX example, do you mean the one on the Select2 examples page? This example formats the response, whereas I just wanted a simple list. Do I still need to format the response with the templateSelection and templateResults?

Thanks again..

Kevin Brown

unread,
Feb 10, 2015, 11:17:56 AM2/10/15
to sel...@googlegroups.com
On 02/10/2015 09:40 AM, Mac Black wrote:
So I removed the json encoding and the output from the script is now 

{"results":[{"id":0,"text":"text name0"}]}

This data, as it stands right here, should be fine for Select2. You wouldn't need a `processResults` method as it does not need any further processing.



which is a valid json format however I'm still not getting any results. The console for the Select2 gives me 2 errors:

Select2: The AJAX results did not return an array in the `results` key of the response.select2.js:3117 (anonymous function)
Uncaught TypeError: Cannot read property 'slice' of undefined select2.js:3613

The first error is because Select2 is not getting the right format from `processResults`. In your case, with your current data, you shouldn't need `processResults` as it should only be used when converting a JSON response to the representation that Select2 is expecting.


I think my example is as simple as it comes, so I've obviously missed something fundamental! 

When you say AJAX example, do you mean the one on the Select2 examples page?

Yes, the one where Select2 is hooked up to the GitHub API for searching repositories.  It's important to note that the GitHub API returns the list of results in the `items` key instead of the `results` key, which is why we use `processResults` to re-map it to what Select2 is expecting.


This example formats the response, whereas I just wanted a simple list. Do I still need to format the response with the templateSelection and templateResults?

You shouldn't need to template the options unless you want to add special markup. In the AJAX example we have the special markup in the results to show the useful information that GitHub brings.

Kevin Brown

Mac Black

unread,
Feb 10, 2015, 12:05:45 PM2/10/15
to sel...@googlegroups.com
It works fine now thank you... and thanks for your patience!

Regards

Mac

stra...@gmail.com

unread,
Feb 12, 2015, 2:43:21 PM2/12/15
to sel...@googlegroups.com
@Mac Black- Can you please post your full code. I (as well as many others) are having trouble getting select2 V4 to work with remote ajax calls and standard response format (id, text). This used to be simple with V3, but it's not working anymore with V4. I've read all the V4 docs, release notes, countless searching for a working example. I can't find anything.

@Kevin Brown - Please forgive my frustration. I feel like I have wasted hours on this though. Seriously! Why is there no documentation or example of using remote ajax on just a simple id,text return result? an example connecting to github with custom formating does not help here. It's too damn confusing to get this V4 working out of the box. V3 was much easier to deal with. I don't have time to search for days for a working remote ajax example, when this should be available right up front. This is how most people are going to need to use the select2 (with remote ajax that returns just the id/text results to build the options). Even the replies to others having the same issue does not spell anything out. What is the big secret here?

Currently, I have he V4 select2 setup as Mac does, no errors are returned in the console when the GET operation is performed. The results are there in the ajax, but these results do not populate the select2 options. it just stays blank, no error, nothing to tell what is wrong. lame! Please, for the sake of not having to answer this same questions from countless others, please provide a JSfiddle or working example code so we can all get on with using select2 V4. Thank you.

Hope this helps

unread,
May 20, 2015, 3:06:39 PM5/20/15
to sel...@googlegroups.com, stra...@gmail.com
@stra...@gmail.com

I too was having a great deal of trouble with AJAX results populating the select2 results box.

I am using php, and json_encode() was not outputting the *exact* format that select2 needs. I needed to add a curly bracket and the text `"results":` to the outside of my json_encode() data.

$jsonData= json_encode($phpData);
$jsonData= "{ \"results\": " . $jsonData. "}";

My final data structure looked like this:
{ "results": [{"id":0,"text":"item1"},{"id":1,"text":"item2"}, ... ]}

I hope this is able to help you!
Reply all
Reply to author
Forward
0 new messages