Select2 removes default options when using ajax

I am trying to set up my predefined selection options in select2 with ajax but when I use ajax and clicking on select2 it removes the html parameters that I had there before, any idea how I can make it leave the parameters as they are, and not delete them until I type some unattractive char?

I believe this is not clear, so I did the violin in both cases so that you better understand

HTML

<select id="e1" style="width:300px"> <option value="AL">Alabama</option> <option value="Am">Amalapuram</option> <option value="An">Anakapalli</option> <option value="Ak">Akkayapalem</option> <option value="WY">Wyoming</option> </select> <select id="e2" style="width:300px"> <option value="AL">Alabama</option> <option value="Am">Amalapuram</option> <option value="An">Anakapalli</option> <option value="Ak">Akkayapalem</option> <option value="WY">Wyoming</option> </select> 

js

 $("#e1").select2({ajax: { url: "https://api.github.com/search/repositories", dataType: 'json', delay: 250, data: function (params) { return { q: params.term, // search term page: params.page }; }, processResults: function (data, page) { // parse the results into the format expected by Select2. // since we are using custom formatting functions we do not need to // alter the remote JSON data return { results: data.items }; }, cache: true }}); $("#e2").select2(); 

select2 ajax and none ajax script example

+3
javascript ajax jquery-select2 jquery-select2-4
source share
1 answer

On the server side of the script where you are processing the search request submitted by the user, return the first 5 elements that should be displayed by default, even if the request is empty.

  $query=$_REQUEST['q']; if (!empty($query)) { //populate the results if the user is typed something in } else { $results=array(); $results[0]['text']=Alabama; $results[0]['id']="idofalabama"; // and so on, for the number of results you want to display when the user didn't input anything in the search box } return json_encode($results); 
-one
source share

All Articles