Select2 JS not showing data from AJAX

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.

Upvotes: 0

Views: 883

Answers (1)

ztadic91
ztadic91

Reputation: 2804

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

Upvotes: 2

Related Questions