How to apply select2 with jquery ajax in Flask application

I am trying to reuse the last example from this select2 page: https://select2.org/data-sources/ajax
( Additional examples This code powers the Github example presented at the beginning of this chapter )

I copied the whole code into my Flask application view and it works fine with returning data from GIT.

Now I try to change the GIT supplied data to my own:

...
  ajax: {
    url: "https://api.github.com/search/repositories",
...

To my Flask route:

...
  ajax: {
    url: '{{url_for("extras_blueprint.test")}}',
...

This route I defined like this:

@extras_blueprint.route('/test', methods=['POST', 'GET'])
def test():
    #antenna is for now hard coded search term which is supposed to come from view
    products = Product.query.filter(Product.name.contains("Audi")).all() 
    results= []
    for product in products:
        small_dict = {}
        small_dict["id"] = product.id
        small_dict["text"] = product.name
        small_dict["full_name"] = product.name
        results.append(small_dict)
    print(results)
    return jsonify(results) 

In the above sample I have hard coded searchTerm “Audi” just because I do not want to pass it yet from the view for simple testing.

However, It is not showing to me any select2 options. I tried also to change this peace from the example:

     params.page = params.page || 1;

      return {
        results: data.items,
        pagination: {
          more: (params.page * 30) < data.total_count
        }

Instead of data.items to data
But also no luck. Any suggestions how to apply this example from select2 to flask application are very welcome.

I assume you are entering a search term in the Select2 (even though your server-side code is currently ignoring it).

Have you tried opening your browser’s developer console and watching the Network tab to see whether the query is actually sent to your server when you type in the Select2? If so, what results are coming back?

Another thing to try is to test the query URL in your browser’s address bar. You should be able to enter the URL of the query endpoint in your browser’s address bar and get a response.

I’m wondering if jsonify(results) actually returns a JSON string that contains an object whose only property is called “results”, or whether it’s returning a JSON string that contains just the array of items. (I’m guessing it’s the latter, and you need to actually return jsonify({"results": results}).

Yes, I am entering search code and my sever is ignoring it, so i have it easier

I did some tests for GIT example:

console.log(data.items);
       return {
           results: data.items,
           pagination: {
             more: (params.page * 30) < data.total_count
           }

It shows this in console:

And then with my own data I need to change data.items to data to display something in console:

console.log(data);
    return {
        results: data,
        pagination: {
         more: (params.page * 30) < data.total_count
        }

Then my data also appears:

but options not appearing

there is this repo which im not sure what is it doing

actually the error is in template

 ``` "<div class='select2-result-repository__avatar'><img src='" + repo.owner.avatar_url + "' /></div>" +``

needed to remove owner because it is something that GIT object contains, but not mine …

What is this repo thing though?

Now i am getting an error 404 for each option line, and it returns 32 items instead 30

but at least now it is displaying items

The repo thing is from the GIT example (“repo” = “repository”). It must be a property (sub-object) of the objects in data.items. So you don’t need that at all in your template.

Your pagination isn’t working because the expression that indicates whether there are more items is comparing against data.total_items; but in your case, data is only an array of items; it doesn’t contain a total_items property, so data.total_items is undefined, and comparing any number to undefined returns false. So the Select2 results list is not paginated and just displays all of the returned results.

I’m not sure that you mean by each “option line” getting a 404 error. A 404 error means the requested resource is not found. What are the URLs that are returning the 404s? Can you take a screen shot of the Network tab in your Developer tools showing the 404s and the URLs that are causing them?

Pagination - indeed it was that.

404 error disappeared so It may be something not related to the question.

May I ask about this repo, how is it passed from this git object?

  templateResult: formatRepo,
  templateSelection: formatRepoSelection
});

function formatRepo (repo) {
  if (repo.loading) {
    return repo.text;
  }

  var $container = $(
    "<div class='select2-result-repository clearfix'>" +
      "<div class='select2-result-repository__avatar'><img src='" + repo.owner.avatar_url + "' /></div>" +

I see it pass to function function formatRepo (repo) but how it works? And in my case I actually removed only owner, not repo, so from repo.owner.avatar_url to repo.owner.avatar_url (I created avatar_url on server side) and it worked.

“formatRepo” is the name of the custom templateResult function that is used in the example code. You can write your own custom result templating function and name it whatever you want (for example, “formatResult”).

When you specify a custom result templating function in the Select2 initialization call, Select2 will automatically pass each item in the result list to that function in order to render that item in the dropdown list. Look at the documentation I linked above; it should answer all your questions.

1 Like