I want to ask how to select default value from ajax to select2? My ajax code:
// Customer
$('.shipper').select2({
placeholder: "Choose Shipper",
selectionTitleAttribute: false,
ajax: {
url: 'getCustomer.php',
dataType: 'json',
data: function (params) {
return {
filter_name: params.term
};
},
processResults: function (data) {
return {
results: $.map(data, function (obj) {
return {id: obj.customer_id, text: obj.name};
})
};
},
cache: true
},
initSelection: function (element, callback) {
return callback({id: "<?php echo $data['customerId']; ?>", text: '<?php echo $shipper['name']; ?>'});
}
});
While my PHP code to fetch data is like this:
<?php
include('config.php');
$json = array();
if (isset($_GET['filter_name'])) {
$clientId = $_GET['filter_name'];
$query = "SELECT * FROM m_customer WHERE c_name LIKE '%$clientId%' AND c_status > 0 ORDER BY c_name ASC LIMIT 0,10";
} else {
$query = "SELECT * FROM m_customer WHERE c_status > 0 ORDER BY c_name ASC LIMIT 0,10";
}
$result = mysqli_query($conn, $query);
while ($row = mysqli_fetch_array($result, MYSQLI_ASSOC)) {
$json[] = array(
'customer_id' => $row['c_id'],
'name' => strip_tags(html_entity_decode($row['c_name'], ENT_QUOTES, 'UTF-8')),
);
}
echo json_encode($json);
?>
I'm creating update page for my PHP files. So I need this select2 is selected from my database. That's why I get data from database then try to set to initSelection
. It's already shows up and selected. But when I press save button (and look at my code from inspect element), the select doesn't have value. So it failed to save (screenshot attached)
I have weird solution:
I put the Option manually with the value and text from DB. It's done! My code become like this:
<select class="shipping form-control" name="shipping_id">
<option value="<?php echo $data['shippingId']; ?>" selected><?php echo $shipping['name']; ?></option>
</select>
But is there any problem/cause further? Because I think it's weird solution... (although it's work)
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.