javascript – select2, can't select AJAX result-ThrowExceptions

Exception or error:

I’m trying to make a select2 list using ajax. I follow the select2 documentation here https://select2.org/data-sources/ajax.

I can’t select result in the list. I belive this has to be some problem within templateResult: formatRepo or templateSelection: formatRepoSelection.

I already search for similar cases here in stackoverflow but can’t really find the solution.

Here’s the jsfiddle http://jsfiddle.net/eruikusu/tL19o6e7/14/

Here’s the code snippet:

<!DOCTYPE html>
<html lang="en">

<head>
    <!-- Required meta tags -->
    <meta charset="utf-8" />
    <meta name="viewport" content="width=device-width, initial-scale=1, shrink-to-fit=no" />

    <!-- Optional JavaScript -->
    <!-- jQuery first, then Popper.js, then Bootstrap JS -->
    <script src="https://ajax.googleapis.com/ajax/libs/jquery/3.4.1/jquery.min.js"></script>
    <script src="https://cdn.jsdelivr.net/npm/popper.js@1.16.0/dist/umd/popper.min.js" integrity="sha384-Q6E9RHvbIyZFJoft+2mJbHaEWldlvI9IOYy5n3zV9zzTtmI3UksdQRVvoxMfooAo" crossorigin="anonymous"></script>
    <script src="https://stackpath.bootstrapcdn.com/bootstrap/4.4.1/js/bootstrap.min.js" integrity="sha384-wfSDF2E50Y2D1uUdj0O3uMBJnjuUD4Ih7YwaYd1iqfktj0Uod8GCExl3Og8ifwB6" crossorigin="anonymous"></script>

    <!-- Bootstrap CSS -->
    <link rel="stylesheet" href="https://stackpath.bootstrapcdn.com/bootstrap/4.4.1/css/bootstrap.min.css" integrity="sha384-Vkoo8x4CGsO3+Hhxv8T/Q5PaXtkKtu6ug5TOeNV6gBiFeWPGFN9MuhOf23Q9Ifjh" crossorigin="anonymous" />

    <!-- select2 -->
    <link href="https://cdn.jsdelivr.net/npm/select2@4.0.13/dist/css/select2.min.css" rel="stylesheet" />
    <script src="https://cdn.jsdelivr.net/npm/select2@4.0.13/dist/js/select2.min.js"></script>

    <title>Anime title selector</title>
</head>

<body>
    <h1>Hello, world!</h1>
    <select id="select_anime" class="form-control select2"> </select>
</body>
<script type="text/javascript">
    $("#select_anime").select2({
        ajax: {
            url: "https://api.jikan.moe/v3/search/anime",
            delay: 250,
            data: function(params) {
                return {
                    q: params.term // search term
                };
            },
            processResults: function(data, params) {
                return {
                    results: data.results
                };
            },
            cache: true
        },
        placeholder: "Search for an anime title",
        minimumInputLength: 1,
        templateResult: formatRepo,
        templateSelection: formatRepoSelection
    });

    function formatRepo(repo) {
        if (repo.loading) {
            return repo.text;
        }
        var $container = $(
            "<span> (" +
            repo.mal_id +
            ") " +
            repo.title +
            "</span>"
        );

        return $container;
    }

    function formatRepoSelection(repo) {
        return repo.title || repo.text;
    }
</script>

</html>
How to solve:

The issue is because Select2 data needs to contain an id and text property for the values to be recognised correctly. Therefore your processResults handler function should look like this:

processResults: function(data, params) {
  return {
    results: data.results.map(item => ({
      id: item.mal_id,
      text: item.title
    }))
  };
},

Here’s a fully working example, including some other improvements to the logic:

$("#select_anime").select2({
  ajax: {
    url: "https://api.jikan.moe/v3/search/anime",
    delay: 250,
    data: (params) => ({ q: params.term }),
    processResults: function(data, params) {
      return {
        results: data.results.map(item => ({
          id: item.mal_id,
          text: item.title
        }))
      };
    },
    cache: true
  },
  placeholder: "Search for an anime title",
  minimumInputLength: 1,
  templateResult: repo => repo.loading ? repo.text : $(`<span>(${repo.id}) ${repo.text}</span>`),
  templateSelection: repo => repo.text
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.4.1/jquery.min.js"></script>
<script src="https://cdn.jsdelivr.net/npm/popper.js@1.16.0/dist/umd/popper.min.js" integrity="sha384-Q6E9RHvbIyZFJoft+2mJbHaEWldlvI9IOYy5n3zV9zzTtmI3UksdQRVvoxMfooAo" crossorigin="anonymous"></script>
<script src="https://stackpath.bootstrapcdn.com/bootstrap/4.4.1/js/bootstrap.min.js" integrity="sha384-wfSDF2E50Y2D1uUdj0O3uMBJnjuUD4Ih7YwaYd1iqfktj0Uod8GCExl3Og8ifwB6" crossorigin="anonymous"></script>
<link rel="stylesheet" href="https://stackpath.bootstrapcdn.com/bootstrap/4.4.1/css/bootstrap.min.css" integrity="sha384-Vkoo8x4CGsO3+Hhxv8T/Q5PaXtkKtu6ug5TOeNV6gBiFeWPGFN9MuhOf23Q9Ifjh" crossorigin="anonymous" />
<link href="https://cdn.jsdelivr.net/npm/select2@4.0.13/dist/css/select2.min.css" rel="stylesheet" />
<script src="https://cdn.jsdelivr.net/npm/select2@4.0.13/dist/js/select2.min.js"></script>
<h1>Hello, world!</h1>
<select id="select_anime" class="form-control select2"> </select>

Leave a Reply

Your email address will not be published. Required fields are marked *