I'm trying to update the select tag option values after submitting the data in the bootstrap modal and that data goes in the select tag. But problem is that we are having to reload the page In order to show those submitted values in the option tag
Select Tag
$user_id = $_SESSION['user_id'];
$select_customer = "select * from customer where user_id='$user_id'";
$select_customer_query = mysqli_query($connection,$select_customer);
<div class="form-group">
<select class="form-control form-control-chosen add-customer-tag" id="invoice_customer_name" name="invoice_customer_name">
<option disabled selected>Customer Name</option>
<?php if(mysqli_num_rows($select_customer_query)>0){
while($customer_result = mysqli_fetch_assoc($select_customer_query)) { ?>
<option><?php echo $customer_result['customer_name']; ?></option>
<?php }} ?>
<option value="add-new-customer">Add New Customer</option>
</select>
</div>
Bootstrap Modal
<div id="add-customer-modal" class="modal fade add-customer-modal" role="dialog">
<div class="modal-dialog">
<div class="modal-content">
<div class="modal-header">
<h4 class="modal-title">Add New Customer</h4>
</div>
<div class="modal-body">
<div class="form-group">
<input type="text" class="form-control" id="customer_name_modal" name="customer_name_modal" placeholder="Customer Name">
</div>
</div>
<div class="modal-footer">
<button type="button" class="btn btn-secondary" data-dismiss="modal">Close</button>
<button type="button" class="btn btn-primary" data-dismiss="modal" id="add-customer-modal-btn">Save</button>
<div class="error_message"></div>
</div>
</div>
</div>
</div>
jQuery Code
$('#add-customer-modal-btn').on('click',function(){
var customer_name_modal = $('#customer_name_modal').val();
$.ajax({
url: 'includes/add-customer-modal.inc.php',
type: 'POST',
data: {customer_name_modal:customer_name_modal},
success: function(add_customer_modal_result){
$('.error_message').html(add_customer_modal_result);
}
});
});
add-customer-modal.inc.php File
<?php
session_start();
include 'db-connection.php';
$user_id = $_SESSION['user_id'];
$customer_name = mysqli_real_escape_string($connection, $_POST['customer_name_modal']);
if(empty($customer_name)){
echo "<span class='alert alert-danger'>Customer name cannot be blank</span>";
} else {
$insert_customer = "insert into customer(user_id,customer_name) values('$user_id','$customer_name')";
$inser_customer_query = mysqli_query($connection,$insert_customer) or die(mysqli_error($connection));
if($inser_customer_query){
echo "<span class='alert alert-success'>Customer has been added</span>";
}
}
?>
I know code is vulnerable to SQL Injection. This is only for testing purposes, so you can ignore it.
Once customer name has been added through bootstrap modal, then it would be inserted in the select tag but it reflects only after reloading the page