I am new to Select2 and am having trouble integrating AJAX. When I search, the results aren't being filtered based on the query.
Here's how it looks: http://i.imgur.com/dAPSSDH.png - The right characters are underlined in the results, but nothing is filtered out. In my non-ajax Select2 and in the examples I've seen, the filtering seems to happen somewhat automatically, so I am hesitant to write a custom filter as there is probably a better one built in already.
Here's my code:
<script>
$("#search_bar").select2({
placeholder: "Search for another Concept",
minimumInputLength: 1,
ajax: { // instead of writing the function to execute the request we use Select2's convenient helper
url: "/concepts/names_for_search",
dataType: 'json',
data: function (term, page) {
return {
q: term, // search term
page: page
};
},
results: function (data, page) {
return { results: data};
}
},
});
</script>
Also, here is an example of my JSON:
[{"id":1,"text":"Limits"},{"id":2,"text":"Derivatives"},{"id":3,"text":"One-Sided Limits"},{"id":4,"text":"Formal Definition of a limit"}]
Any ideas? Hopefully I am just doing something stupid and it is a quick fix. Thanks in advance for any help.
You will need to write a custom filter on server side to filter the results. What you type in the box is saved in 'term' and then 'q' is sent as a request parameter with the ajax call. So the ajax call to
url:"/concepts/names_for_search?q=deri"
should only return the filtered results and not all the results.
Update
Select2 will make an AJAX call every time you type in the search box. You have to filter the results on server side and then return the results based on the text in search box.
I am using it in my JSP/Servlet application as below
protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException
{
String searchTerm = request.getParameter("q");
String json = getOptions(searchTerm);
//getOptions method will return a string of in JSON format
//[{"id":"1","name":"Derivatives"}]
response.getWriter().write(json);
}
Your JavaScript code is correct.
I found Select2 is used here. If you open the link http://www.indiewebseries.com/search?q=ind and http://www.indiewebseries.com/search?q=in the results obtained are different and based on the 'q' parameter.
While in you case, the results for calls to url '/concepts/names_for_search?q=d' and '/concepts/names_for_search?q=deri' are the same(i.e. not filtered)
This question was asked on the github project and the answer was: filter on the server side.
The default filter function called when AJAX is not used is present in the Select2 documentation on the matcher
parameter:
function(term, text) { return text.toUpperCase().indexOf(term.toUpperCase())>=0; }
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With