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.

1

1 Answer 1

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

Sign up to request clarification or add additional context in comments.

2 Comments

thanks alot! it was just syntax writing style issue. i fixed it with this: return { results: newResults };
Glad I could help!

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.