how to fill combo in modal open not on page load - javascript

I have a modal containing a combobox,this combobox is populated from database, i want the combobox filled when the modal is opened not on page load,how can this be done?
div class="modal fade" id="modal-DeleteFrm">
<div class="modal-dialog modal-sm" style="width:300px;">
<div class="modal-content">
<div class="modal-header">
<button type="button" class="close" data-dismiss="modal">×</button>
<h3 class="modal-title">Delete Farmer</h3>
</div>
<div class="modal-body">
<div class="well" style="margin-bottom: 0px;padding: 10px;">
<div>
<label class="Modallabel">Farmer Name:</label>
</div>
<div>
<select style="width:100%;background-color: #101d49;color:#ffffff;padding-bottom: 5px;" name="FarmerName" id="FarmerName">
<option value="">Select Farmer Name</option>
<!--populate value using php-->
<?php
$stmt ="SELECT * FROM Farmers";
foreach ($conn->query($stmt) as $row) {
$FarmerName = $row['first_name_'].' '.$row['last_name_'];
?>
<option value="<?php echo $row['Farmer_ID'];?>"><?php echo $FarmerName;?></option>
<?php
}
?>
</select>
</div>
</div>
</div>
<div class="modal-footer">
<button id="submitbtn" name="submitbtn" type="button" class="btn btn-success btn-md" style="text-align:center;margin:0;width: 75px;" onclick="DeleteEntry('DeletedFarmer')">Delete</button>
<button type="button" class="btn btn-secondary btn-md" data-dismiss="modal" onclick="CancelModal()" style="text-align:center;font-weight: bold;">Cancel</button>
</div>
</div>
</div>

You need to set a callback to your modal opening event as this code. Then populate your select into it:
$('#modal-DeleteFrm').on('shown.bs.modal', function () {
// write your codes here...
})

You should probably be doing an ajax request when the modal button is clicked. i.e.
$('.modal-DeleteFrm.').on('click', function(){
$.ajax([
url: YOUR-POST-URL
dataType: json,
method: POST,
success: function() {
// Do your appending here
}
])
})
Which would send a POST request and return the data back as JSON.
You could then append this to your modal form using javaScript .append()

Related

I don't want to reload the page with post request

I create form, the popup window (in the same file with the form) and the script that creates the post request when the user clicks the button, but when I click the button the page relaoded automatically and the popup window never appears
*I want to pass a parameter from the form to popup window in order to identify the product that the user selected.
My code is below:
*The form is inside of a loop in order to create many items
index.php
while($row = mysqli_fetch_assoc($select_all_products)) {
$product_id = $row['id'];
$product_name = $row['name'];
$product_price1 = $row['price1'];
$product_price2 = $row['price2'];
$product_price3 = $row['price3'];
$product_image= $row['photo'];
?>
<div class="col-lg-6 col-md-6 item-entry mb-4">
<form method="post" >
<a href="#" class="product-item md-height bg-gray d-block">
<?php echo "<img width='300px' height='300px' src='images/$product_image' alt='Image' class='img-fluid'>"; ?>
</a>
<h2 class="item-title"><?php echo $product_name; ?></h2>
<input id="id" type="hidden" name="id" value="<?php echo $product_id; ?>">
<label>shop1: </label>
<strong class="item-price"><?php echo $product_price1 ."\xE2\x82\xAc".str_repeat(' ', 5) ; ?></strong>
<label>shop2 </label>
<strong class="item-price"><?php echo $product_price2 ."\xE2\x82\xAc".str_repeat(' ', 5) ; ?></strong>
<label>shop3 </label>
<strong class="item-price"><?php echo $product_price3 ."\xE2\x82\xAc" .str_repeat(' ', 3) ; ?></strong>
<button type="submit" onclick="loadData(this.getAttribute('data-id'));" data-id="<?php echo $product_id; ?>" class="btn btn-primary btn-sm rounded" data-toggle="modal" data-target="#myModal">Change Price<i class="fas fa-tags"></i></button>
</form>
</div>
<?php
}
?>
popup window :
<!-- Modal -->
<div class="modal fade" id="myModal" tabindex="-1" role="dialog" aria-labelledby="myModalLabel" aria-hidden="true">
<div class="modal-dialog">
<div class="modal-content">
<div class="modal-header">
<button type="button" class="close" data-dismiss="modal"><span aria-hidden="true">×</span><span class="sr-only">Close</span></button>
<h4 class="modal-title" id="myModalLabel">Modal title</h4>
</div>
<div class="modal-body">
</div>
<div class="modal-footer">
<button type="button" class="btn btn-default" data-dismiss="modal">Close</button>
<button type="button" class="btn btn-primary">Save changes</button>
</div>
</div>
</div>
</div>
script :
<script type="application/javascript">
function loadData(id) {
id.preventDefault();
$.ajax({
url: "price.php",
method: "POST",
data: {get_data: 1, id: id},
success: function (response) {
console.log(response);
}
});
}
</script>
From the console log I found that the post request send it but with reload page and for this reason the the popup window never appears. 1
What I can do in order the page not reloaded ,the pop up appeared get the post request?
Thank you
To prevent the form from being submitted and hence the page refresh, you should call preventDefault on the form's onsubmit event, like this: <form method="post" onsubmit="event.preventDefault()">. It also works returning false like this: <form method="post" onsubmit="return false">.
I've made an example with the php part removed so you can see. Hope this helps.

How to fix ajax runs when i try to select option from dropdown

My form contains two select elements. Submission should occur via AJAX only when the onclick event handler bound to button#assignrole is triggered.
But currently, the AJAX call is fired as soon as I select an option from the "User" dropdown:
I have tried to disable all other scripts in my footer, header etc and only kept jQuery v3.4.1
<!-- Assign Role To User -->
<div class="modal fade" id="assignrole" tabindex="-1" role="dialog" aria-labelledby="myModalLabel">
<div class="modal-dialog" role="document">
<div class="modal-content">
<form>
<div class="modal-header">
<button type="button" class="close" data-dismiss="modal" aria-label="Close"><span aria-hidden="true">×</span></button>
<h4 class="modal-title" id="myModalLabel">Assign Role To User</h4>
</div>
<div class="modal-body">
<div class="form-group">
<label for="selectuser">Select User</label>
<select class="form-control" id="selectuser">
<?php foreach ($users as $user): ?>
<option value="<?= $user['id'] ?>">
<?= $user['username'] ?>
</option>
<?php endforeach; ?>
</select>
</div>
<div class="form-group">
<label for="selectrole">Select Role</label>
<select class="form-control" id="selectrole" data-live-search="false">
<?php foreach ($roles as $role): ?>
<option value="<?= $role['id'] ?>">
<?= $role['role_name'] ?>
</option>
<?php endforeach; ?>
</select>
</div>
</div>
<div class="modal-footer">
<button type="button" class="btn btn-default" data-dismiss="modal">Close</button>
<button type="submit" id="assignrole" class="btn btn-primary">Save changes</button>
</div>
</form>
</div>
</div>
</div>
$(document).ready(function() {
var base_url = "http://127.0.0.1/ci3/";
$("#assignrole").on('click', function() {
var user_id = $('#selectuser option:selected').attr('value');
var role_id = $('#selectrole option:selected').attr('value');
$.ajax({
url: base_url + "backend/assign_role",
method: 'POST',
data: {
"user_id": user_id,
"role_id": role_id
},
dataType: 'json',
success: function(data) {
if (data.status == 1) {
alert("Data Send Success");
}
},
error: function(data) {
alert("maybe your login session timed out, try to login again!");
}
});
});
});
no errors show up
It seems that you have duplicate ID's.
Here:
<div class="modal fade" id="assignrole" tabindex="-1" role="dialog" aria-labelledby="myModalLabel">
And here:
<button type="submit" id="assignrole" class="btn btn-primary">Save changes</button>
So that means that when you add the click event it will be set on the first hit of that ID. Which in your case is the modal element.
$("#assignrole") // <div class="modal fade" id="assignrole" tabindex="-1" role="dialog" aria-labelledby="myModalLabel">
Changing the ID's of one of the two elements will fix the click issue.
It's because you selector ("#assignrole") is not appropriate.
you have 2 html element with same ids:
<button type="submit" id="assignrole" class="btn btn-primary">Save changes</button>
<div class="modal fade" id="assignrole" tabindex="-1" role="dialog" aria-labelledby="myModalLabel"></div>
remove the modal id.

Insert data from modal to database

I want to make a form appear on a popup window when I click "Add" button. So I am using a modal to show a PHP form but when I tried to save the data inserted into the form into database, it does not work. When I clicked save, a weird URL came out as so :
.../pembelitkatakutest.php?image=025pikachu_xy_anime_3.png&save=
I am not sure, but I think the URL should not have the "image=025pikachu_xy_anime_3.png&" part.
My code is as below:
<button type="button" class="btn btn-primary" data-toggle="modal" data-target="#myModal">Add Tongue Twister</button><br><br><br>
<!-- Modal -->
<div class="modal fade" id="myModal" tabindex="-1" role="dialog" aria-labelledby="myModalLabel" aria-hidden="true">
<div class="modal-dialog">
<div class="modal-content">
<div class="modal-header">
<button type="button" class="close" data-dismiss="modal"><span aria-hidden="true">×</span><span class="sr-only">Close</span></button>
<h4 class="modal-title" id="myModalLabel">Add Tongue Twister</h4>
</div>
<div class="modal-body">
<form method = "POST">
<div class="form-group">
<label for="usr">Please Choose a Picture:</label>
<input type="file" name="image">
<script type="text/javascript">
$(document).ready(function() {
$(window).keydown(function(event){
if(event.keyCode == 13) {
event.preventDefault();
return false;
}
});
});
</script>
</div>
<div class="form-group">
<label for="pwd">Please write the tongue twister:</label>
<input type="text" rows = "3" class="form-control">
</div>
</div>
<div class="modal-footer">
<button type="button" class="btn btn-default" data-dismiss="modal">Close</button>
<button type="submit" class="btn btn-primary" name="save">Save changes</button>
<?php if(isset($_POST['save']))
{
//target folder to keep the media
$target = "images/".basename($_FILES['image']['name']);
//get all submitted data from form
$image = $_FILES['image']['name'];
$text = $_POST['text'];
if(!empty($_FILES['image']['name']))
{
$sql = "INSERT INTO pembelitkataku(image, text) VALUES ('$image','$text')";
mysqli_query($db, $sql);
}
else
{
$message = "Sila pilih semua fail";
echo "<script type='text/javascript'>alert('$message');</script>";
}
move_uploaded_file($_FILES['image']['tmp_name'], $target);
}
?>
</div>
</form>
</div>
May I know what went wrong in my code and what can I do to fix it ?
If it is possible, I want to avoid using Javascript as it is very confusing to understand.
Thank you.
Use <form method="POST" enctype="multipart/form-data">
Because by default your code is making GET request but your PHP code want to receive a POST request. You can see it in this line of code :
if(isset($_POST['save']))

Get data-id from modal and use it to get db rows

I have a button that opens modal box. However i saved id value to that button in data-id and i want to use that value to generate content in modal box from DB.
<?php while($car = mysqli_fetch_assoc($sqlquery)) : ?>
<div class="col-md-4 text-center">
<h4><?=$car['model'];?></h4>
<img src=<?php echo $car['image'] ?>/>
<br/>
<a id="firstButton" type="button" class="show-modal btn btn-default" data-id="<?=$car['id']?>">DETAILS</a>
</div>
<?php endwhile ?>
This is how i generate the button... I need to get the data-id value somewhat to the modal box.
$(document).ready(function(){
// Otevre modal
$('.show-modal').click(function(){
var productID = $(this).attr('data-id');
//$.post('detailbox.php', {data: productID}, function(data){
// console.log(data);});
$("#itemBox").modal('show');
// kod co otevre modal, mkrni na bootstrap manual jak je otevira nebo si otevreni nadefinuj sa
$('.product_id').val(productID);
});
// Pridani do kosiku v modalu
$('.add-to-basket').click(function(){
var productID = $('.product_id').val();;
// skryty input do ktere si zapsal ID produktu po otevreni modalu
document.cookie= 'data='+productID;
$.ajax({
type: 'POST',
cache: false,
data: {id : productID},
url: 'cart/cartid.php', // tomuto souboru predas idecko produktu, zapises do kosiku atd.
success: function(data) {
window.location.replace("/shop/cart/cart.php")
alert("Product was added to basket");
// treba nejaka hlaska, ze byl pridan do kosiku
}
});
});
});
This JS gets the data-id and i can get it within input box, i tried to move the while cycle a bit down so it doesnt cycle whole modal, only the things i need to generate, but i cannot get data from input box that i need.
?php while($details = mysqli_fetch_assoc($sqlquery)) : ?>
<div class="container">
<!-- Modal -->
<div class="modal fade" id="itemBox" role="dialog">
<div class="modal-dialog modal-lg">
<!-- Modal content-->
<div class="modal-content">
<div class="modal-header">
<button type="button" class="close" data-dismiss="modal">×</button>
</div>
<div class="modal-body display-content">
<div class="container-fluid">
<div class="col-md-4"><img src=<?php echo $details['image'];?> class="image-responsive">
<div class="col-sm-6">
<form action="add_cart.php" method="post">
<div class="form-group">
<label for="quantity">Quantity:</label>
<input type="text" class="form-control" id="quantity" name="quantity">
</div>
</form>
</div>
<div class="col-sm-6">
<br/>
<!-- Getting product ID from JS, -->
<div class="product_id">
<input class="product_id" type="text" id="input_product_id" name="input_product_id" value=""/>
</div>
<button type="button" class="add-to-basket btn btn-success" >ADD TO CART</button>
</div>
</div>
<div class="col-md-1"></div>
<div class="col-md-7" id="desc">
<p><b>Model:</b> <?php echo $details['model'];?></p>
<p><b>Engine:</b> <?php echo $details['engine'];?></p>
<h4>Description</h4>
<p><?php echo $details['description'];?></p>
<hr>
<hr>
</div>
</div>
</div>
<div class="modal-footer">
<button type="button" class="btn btn-default" data-dismiss="modal">Close</button>
</div>
</div>
</div>
</div>
</div>
<?php endwhile; ?>

load bootstrap modal as alert after inserting data to database

im new to php and still learning. i tried to customized bootstrap template and tried to connect a form to a database.
insert.php
$con=mysqli_connect("localhost","root","","finalproject");
// Check connection
if (mysqli_connect_errno())
{
echo "Failed to connect to MySQL: " . mysqli_connect_error();
}
$sql="INSERT INTO stokbarang (Merek, Tipe, Harga)
VALUES
('$_POST[merek]','$_POST[tipe]','$_POST[harga]')";
if (!mysqli_query($con,$sql))
{
die('Error: ' . mysqli_error($con));
}
header("Location: stock.php");
and a page where the form is stock.php, the form is below :
<form name="sentMessage" class="well" id="contactForm" novalidate action = "insert.php" method = "post">
<legend>Masukkan Data</legend>
<div class="control-group">
<div class="controls">
<label>Merek Mobil</label>
<input type="text" class="form-control" placeholder="Merek mobil" id="merek" required
data-validation-required-message="Masukkan Merek mobil" name = "merek"/>
<p class="help-block"></p>
</div>
</div>
<div class="control-group">
<div class="controls">
<label>Tipe Mobil</label>
<input type="text" class="form-control" placeholder="Tipe Mobil" id="email" required
data-validation-required-message="Masukkan tipe mobil" name = "tipe"/>
</div>
</div>
<div class="control-group">
<div class="controls">
<label>Harga</label>
<input type="number" class="form-control" placeholder="Harga"
id="email" required
data-validation-required-message="Masukkan harga mobil" name = "harga"/>
</div>
<br>
<div id="success"> </span></div> <!-- For success/fail messages -->
<br>
<button type="submit" class="btn btn-primary pull-right">Insert</button><br/><br>
</form>
the form is work and i can insert the data by clicking Insert button to database.
Now i want to add a modal as alert after the form is submitted to database in stock.php
i modified the Insert button as following
<button type="submit" class="btn btn-primary pull-right" data-toggle="modal" data-target="#myModal">Insert</button><br/><br>
here is the modal :
<!-- Modal -->
<div class="modal fade" id="myModal" tabindex="-1" role="dialog" aria-labelledby="myModalLabel" aria-hidden="true">
<div class="modal-dialog">
<div class="modal-content">
<div class="modal-header">
<button type="button" class="close" data-dismiss="modal" aria-hidden="true">×</button>
<h4 class="modal-title" id="myModalLabel">SUCCESS</h4>
</div>
<div class="modal-body">
<p>Data Inserted!!</p>
</div>
<div class="modal-footer">
<button type="button" class="btn btn-default" data-dismiss="modal">Close</button>
</div>
</div><!-- /.modal-content -->
</div><!-- /.modal-dialog -->
</div><!-- /.modal -->
but it seems like the button only trigger the modal to appear without submit the form to database. Any suggestion to make the modal appear after successful inserting data to database (after redirecting to stock.php)? or maybe there is better way to make alert after redirect? thank you for your time and help :)
change the header location on insert.php as below :
header("Location: stock.php?sucsess=true");
then stock.php on the head :
<script type="text/javascript">
<?php
if ($_GET['sucsess'] =='true'){
echo '$(function() {
$( "#myModal" ).dialog();
});'
}
?>
</script>
here is a demo only for the alert demo

Categories