I have a select2 that's used to add multiple employees to a work permit. Adding the employees works with no issues but when the permit is viewed I need the added employees to be pre-selected on the select2. I can retrieve the values from the DB via ajax using a JSON string but the select2 only shows each value one at a time rather than as a multi select. Multiple is set to true when the select2 is generated.
My HTML page code is below
<legend><h5 class="text-semibold">Employees</h5></legend>
<div class="row">
<div class="col-md-8 col-md-offset-2">
<div id="select_employee_div" class="content-group-lg">
<label class="control-label text-bold">Select Employees *</label>
<select id="select_employee" class="form-control multi-select-search">
</select>
</div>
</div>
</div>
My select2 initialisation code is below
// Select with search
$('.multi-select-search').select2({
multiple: true
});
My ajax code is below.
$.ajax({
type: "POST",
url: 'php_files/permit_php_files/permit_employee_process.php',
dataType: 'JSON',
data: {
permit_id: $('#permit_id').val()
},
success: function(data) {
var my_obj = data;
$.each(my_obj, function (i, z) {
$("#select_employee").val(my_obj[i].employee_id).trigger('change');
});
}
});
My PHP Code is below
$stmt = $mysqli->prepare("SELECT employee_id FROM tbl_permit_employee WHERE permit_id = ?");
$stmt->bind_param("i", $permit_id);
$stmt->execute();
$stmt->store_result();
$stmt->bind_result($employee_id);
$row_array = array();
while($stmt->fetch()) {
$tmp = array();
$tmp['employee_id'] = $employee_id;
array_push($row_array, $tmp);
}
$stmt->close();
echo json_encode($row_array);
The problem is in success handler of ajax request: you have to pass an array to Select2 val()
function (see https://select2.org/programmatic-control/add-select-clear-items#selecting-options), like in the code below:
var arr = [];
for (var i in data) {
arr.push(data[i].employee_id);
}
$("#select_employee").val(arr).trigger('change');
Here is a working jsfiddle: https://jsfiddle.net/beaver71/h92jmy2w/
P.S.: ajax is simulated via echo feature