Dynamically add item to jQuery Select2 control that uses AJAX

In case of Select2 Version 4+

it has changed syntax and you need to write like this:

// clear all option
$('#select_with_blank_data').html('').select2({data: [{id: '', text: ''}]});

// clear and add new option
$("#select_with_data").html('').select2({data: [
 {id: '', text: ''},
 {id: '1', text: 'Facebook'},
 {id: '2', text: 'Youtube'},
 {id: '3', text: 'Instagram'},
 {id: '4', text: 'Pinterest'}]});



//  append option
$("#select_with_data").append('<option value="5">Twitter</option>');
$("#select_with_data").val('5');
$("#select_with_data").trigger('change');

This is a lot easier to do starting in select2 v4. You can create a new Option, and append it to the select element directly. See my codepen or the example below:

$(document).ready(function() {
    $("#state").select2({
      tags: true
    });
      
    $("#btn-add-state").on("click", function(){
      var newStateVal = $("#new-state").val();
      // Set the value, creating a new option if necessary
      if ($("#state").find("option[value=" + newStateVal + "]").length) {
        $("#state").val(newStateVal).trigger("change");
      } else { 
        // Create the DOM option that is pre-selected by default
        var newState = new Option(newStateVal, newStateVal, true, true);
        // Append it to the select
        $("#state").append(newState).trigger('change');
      } 
    });  
});
<link href="https://cdnjs.cloudflare.com/ajax/libs/twitter-bootstrap/3.3.6/css/bootstrap.min.css" rel="stylesheet"/>
<link href="https://cdnjs.cloudflare.com/ajax/libs/select2/4.0.1/css/select2.min.css" rel="stylesheet"/>

<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/twitter-bootstrap/3.3.6/js/bootstrap.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/select2/4.0.1/js/select2.min.js"></script>


<select id="state" class="js-example-basic-single" type="text" style="width:90%">
  <option value="AL">Alabama</option>
  <option value="WY">Wyoming</option>
</select>
<br>
<br>
<input id="new-state" type="text" />
<button type="button" id="btn-add-state">Set state value</button>

Hint: try entering existing values into the text box, like "AL" or "WY". Then try adding some new values.


This provided a simple solution: Set data in Select2 after insert with AJAX

$("#select2").select2('data', {id: newID, text: newText});