Back

Populating a column from database into select2 via jquery


I'm trying to populate tags from the database 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]); // I tried both returns but non have shwn data in the select tag.
               return response()->json($tag_list);

The following is the Jquery that brings back the tags :

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


             url: '{{ url("/gettag") }}',
             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 :

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

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

 [{"t_name":"Java"},{"t_name":"C++"},{"t_name":"PHP"}]
Cameron replied 3 days ago

https://makitweb.com/loading-data-remotely-in-select2-with-ajax/ as noted here

NOTE – While creating associative array for initialize the Array make sure that their you have defined id and text keys otherwise the HTML element will not be initialized.

you may need to

 return $tag_list->map(function($tags) {
               
                return [ 'id' => $tags->id, 'text' => $tags->t_name ];
            });


Sign in to participate in this thread!



We'd like to thank these amazing companies for supporting us