Vijaysinh Parmar
Vijaysinh Parmar

Reputation: 927

How to make select2 dropdown using Ajax Data Source with each new request?

I am using select2 js for multiple optgroup inside select Box.. I am getting formatted JSON from AJAX Success Call, below is my code. It's appending to select box but its merging with existing data. I want to show only Return Ajax Data in the select box.. I have tried with select destroy and reinialize but it's not working. Please help me on how to make new data only populate in select2.enter image description here

$.post('/get_ajax_data/',{custom_param:1}, function(data){ 
        var result = data.result; 
        $("#client1_select").select2({ data:result }); 
        $('#client1_select').trigger("change"); 
    });

Upvotes: 1

Views: 2267

Answers (1)

gaetanoM
gaetanoM

Reputation: 42054

issue is an existing select box is not replacing with new data but it's just appending with old data..

You need to empty the select before adding new items (I used a button to simulate ajax call):

var result = [{
    "text": "ClientName + Version data is AJAX",
    "children": [{"id": "test1", "text": "test1", "disabled": true}, {
        "id": "test2",
        "text": "test2",
        "selected": "true",
        "disabled": false
    }, {"id": "test3", "text": "test3", "disabled": true}]
}, {
    "text": "Variant",
    "children": [{"id": "1_variant", "text": "single"}, {"id": "2_variant", "text": "dual"}]
}];


$('#client1_select').select2({data: result});
$('#btn').on('click', function (e) {
    $("#client1_select").empty().select2({data: result});
})
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<link href="https://cdnjs.cloudflare.com/ajax/libs/select2/4.0.8/css/select2.min.css" rel="stylesheet"/>
<script src="https://cdnjs.cloudflare.com/ajax/libs/select2/4.0.8/js/select2.min.js"></script>


<button id="btn">Click me</button>
<select id="client1_select" name="states[]" multiple="multiple">
</select>

Upvotes: 1

Related Questions