Abdallah Sakre
Abdallah Sakre

Reputation: 915

Populating a column from database into select2 via jquery

I'm trying to populate tags from DB into a select2 field. The data is returned in the inspect mode, but not populating in the select2 field. I have a tags table with the tag_id and tag_name fields. The following is the code from the controller that fetches and returns the tags :

    public function getTag()
      {

     $tag_list = DB::table('tags')
     ->select('t_name')
     ->get();


            return response()->json(['tag_n' => $tag_list]);

The following is the Jquery that brings back the tags :

<script>
    $(document).ready(function() {
  $("#catBox").select2({
       placeholder:"Select and search",
       ajax:{


             url: urlTag ,
             type: 'GET' ,
             dataType: 'json',
             delay: 250,
             data:function(params){
                return{
                    tag_n:params.term
                };
             },
             processResults:function(response){

                return{
                    results: response
                };
             },

          cache:true
       }
  });
});

</script>

The route and the route url :

    <script>
        var urlTag = '{{ route('getTag') }}';
    </script>

Route::get('/gettag', [
    'uses' => 'PostController@getTag',
    'as' => 'getTag'
]);

The data is returned in the inspect mode, but not populating in the select2 field.

enter image description here

The following is the Select tag :

                   <select class="js-example-basic-multiple" multiple="multiple" name="catBox[]" id="catBox" style ="width:250px">

                    </select>   

Upvotes: 1

Views: 294

Answers (1)

Kaushik Makwana
Kaushik Makwana

Reputation: 2576

return data from a server like this:

[{t_name : "PHP"},{t_name : "TEST"},{t_name : "DEMO"}] insted of pass with `{a_tag : [{t_name : "PHP"},{t_name : "TEST"},{t_name : "DEMO"}]}`





$("#catBox").select2({
      tags: true,
      tokenSeparators: [",", " "],
      createSearchChoice: function(term, data) {
        if ($(data).filter(function() {
          return this.text.localeCompare(term) === 0;
        }).length === 0) {
          return {
            t_name: term
          };
        }
      },
      multiple: true,
      ajax: {
        url: urlTag ,
        dataType: "json",
        data: function(term, page) {
          return {
            q: term
          };
        },
        results: function(data, page) {
          return {
            results: data
          };
        }
      }
    });

Upvotes: 1

Related Questions