Home > Back-end >  Select2 search does not work with JSON File
Select2 search does not work with JSON File

Time:09-26

I am using Select2, if I add data with option tag, search system works successfully but I imported with JSON, it's not working.

HTML

<head>
<link href="https://cdn.jsdelivr.net/npm/[email protected]/dist/css/select2.min.css" rel="stylesheet" />
<!-- CSS only -->
<link href="https://cdn.jsdelivr.net/npm/[email protected]/dist/css/bootstrap.min.css" rel="stylesheet" integrity="sha384-F3w7mX95PdgyTmZZMECAngseQB83DfGTowi0iMjiWaeVhAn4FJkqJByhZMI3AhiU" crossorigin="anonymous">
<script src="https://cdn.jsdelivr.net/npm/[email protected]/dist/js/select2.min.js"></script>
<!-- JavaScript Bundle with Popper -->
<script src="https://cdn.jsdelivr.net/npm/[email protected]/dist/js/bootstrap.bundle.min.js" integrity="sha384-/bQdsTh/da6pkI1MST/rWKFNjaCP5gBSY4sEBT38Q/9RBh9AH40zEOg7Hlq2THRZ" crossorigin="anonymous"></script>
</head>
<div id="banner-message">
<select id="allowedCategories" class="form-control"></select>
</div>

JS

// Create countries dropdown
        $('#allowedCategories').select2({
            placeholder: 'Select allowed categories',
            selectOnClose: false,
            tags: false,
            tokenSeparators: [',', ' '],
            ajax: {
                dataType : "json",
                url      : "https://api.jsonbin.io/b/614ef51eaa02be1d444e64fd",
            },
        });

enter image description here

Clickable, writeable but there is no filtration

CodePudding user response:

Select2 will call your ajax URL to search data. In your case, it calls to https://api.jsonbin.io/b/614ef51eaa02be1d444e64fd?term=baby&_type=query&q=baby

You can see the requests in the below image.

Select2 call to json file

Select2 will issue a request to the specified URL when the user opens the control (unless there is a minimumInputLength set as a Select2 option), and again every time the user types in the search box. By default, it will send the following as query string parameters:

And this is the select2 document, https://select2.org/data-sources/ajax#request-parameters

So you have to modify your JSON/API to let it can search data. Or you should get the data from JSON and use it to build option tag to let the normal filter works.

CodePudding user response:

no filter in your api json to return specific response, test with other api

  • Related