0

I am trying to use select2 js latest version for fetching ajax results, but i am getting the following error:

jQuery.Deferred exception: Cannot read property 'results' of undefined
TypeError: Cannot read property 'results' of undefined

jQuery version i am using: jquery-3.2.1.min

Bootstrap version i am using: 4

Here is my code:

$(document).ready(function(){
      $('#category').select2({
       placeholder: 'Subjects',
       minimumInputLength: 3,
       allowClear: true,
       ajax:{
        url: "<?php echo base_url(); ?>library/ajax-categories",
        dataType: "json",
        delay: 250,
        data: function(params)
        {
         return{
          search: params.term,
          type: 'public'
         };
        },
        processResults: function(data, page)
        {
         var newResults = [];

         $.each(data, function(index, item)
         {
          newResults.push({
           id: item.CategoryID,
           text: item.CategoryName
          });
         });
         return
         {
          results: newResults
         }
        }
       }
      });
     });
<script src="https://code.jquery.com/jquery-3.2.1.min.js"></script>
<select class="select2 form-control" name="category[]" id="category" placeholder="Choose Subjects" multiple>
    </select>

Response I am getting from serverside script:

[
 {"CategoryID":"1","CategoryName":"A Name"},
 {"CategoryID":"2","CategoryName":"B Name"},
 {"CategoryID":"3","CategoryName":"C Name"}
] 

I convert the following response in the select2 pattern that is "id, text" as you can see in my JS code.

Kindly help me out in resolving this error.

dpr
  • 10,591
  • 3
  • 41
  • 71
  • Possible duplicate of [Select2 JS Loading remote data with Ajax](https://stackoverflow.com/questions/28977996/select2-js-loading-remote-data-with-ajax) – Master Yoda Nov 20 '17 at 14:49

1 Answers1

2

It looks like a syntax issue. Reformat your return statement from the processResults function like below. The problem is in the return statement.

  return {
      results: newResults,
  };

JS engines will convert your statement to this:

return;
{
   results: newResults 
}

Additional info here and here

ztadic91
  • 2,774
  • 1
  • 15
  • 21