How to create multiple modals in a document using jQuery and Bootstrap? - javascript

The following function is able to open only one modal since it uses element ID.
How do I expand this function to open multiple modals?
HTML / PHP part of the code (Notice the that is supposed to open the model)
$getUsers = 'SELECT * FROM users';
$result = $pdo->prepare($getUsers);
$result->execute();
while ($row = $result->fetch(PDO::FETCH_ASSOC)) {
if ($row['usergroup'] === "Admin") {
echo "<tr class='table-danger'>";
} else {
echo "<tr>";
}
echo "<td><center>" . $row['username'] . "</center></td>";
echo '<td><center>View</center></td>';
echo "</tr>";
}
Modal
<div class="modal fade" id="userInfoModal" role="dialog" aria-labelledby="exampleModalLabel" aria-hidden="true">
<div class="modal-dialog modal-dialog-centered modal-lg" role="document">
<div class="modal-content">
<div class="modal-header">
<h5 class="modal-title" id="exampleModalLabel">Info</h5>
<button type="button" class="close" data-dismiss="modal" aria-label="Close">
<span aria-hidden="true">×</span>
</button>
</div>
<div id="userModalBody" class="modal-body">
</div>
</div>
</div>
</div>
Javascript
$(document).ready(function() {
$('#openUserInfoModal').on('click',function(){
var dataURL = $(this).attr('data-href');
$('#userModalBody.modal-body').load(dataURL,function(){
$('#userInfoModal').modal({show:true});
});
});
});
Once again, the first row that is displayed, you can click the a href and it will open the modal and display the user info. After the first row, clicking the a href does nothing, and does not open the modal.
Also if you delete the first row / delete the user, and the second row now becomes the first one, you can click the a href and it'll display the users data.
I'm really not sure what is causing this issue, but thanks for any help.

The reason for this, is that you are duplicating the id of the a element. So, when you click on any of them, jQuery is actually using only the first one. So, you would need to change it, so as instead of using an id, you would use a class to open the modal.
PHP
$getUsers = 'SELECT * FROM users';
$result = $pdo->prepare($getUsers);
$result->execute();
while ($row = $result->fetch(PDO::FETCH_ASSOC)) {
if ($row['usergroup'] === "Admin") {
echo "<tr class='table-danger'>";
} else {
echo "<tr>";
}
echo "<td><center>" . $row['username'] . "</center></td>";
echo '<td><center>View</center></td>';
echo "</tr>";
}
jQuery
$(document).ready(function() {
$('.openUserInfoModal').on('click',function(){
var dataURL = $(this).attr('data-href');
$('#userModalBody.modal-body').load(dataURL,function(){
$('#userInfoModal').modal({show:true});
});
});
});

Related

Modal window will not open after paginating retrieved data from the database

I have built an image gallery using the Bootstrap framework, php, SQL and jQuery where users can click a thumbnail to see their selected image enlarged inside a modal window. All the images are stored in a database. The code worked as expected until I paginated the gallery. Now, when a thumbnail is clicked, the modal window does not open. Can anyone suggest a fix for this problem? I have tried some solutions myself but none have worked so far. Many thanks.
gallery.php code:
<div class='row' id='pagination_data'>
<!--Fetch and display images from database -->
<?php ?>
</div>
<!--Bootstrap modal window -->
<div class="modal fade" id="imagemodal" tabindex="-1" role="dialog" aria-labelledby="myModalLabel" aria-hidden="true">
<div class="modal-dialog modal-xl">
<div class="modal-content">
<div class="modal-body">
<button type="button" class="close" data-dismiss="modal"><span aria- hidden="true">×</span><span class="sr-only">Close</span></button>
<img src="" class="imagepreview" style="width: 100%;" >
</div>
</div>
</div>
</div>
<script>
//PAGINATION SCRIPT
$(document).ready(function(){
//when fucntion is called fetch data from gallery table
load_data();
function load_data(page) {
$.ajax({
url:"pagination.php",
method: "POST",
data:{page:page},
success:function(data){
$('#pagination_data').html(data);
}
})
}
$(document).on('click', '.pagination_link', function() {
var page = $(this).attr("id");
load_data(page);
});
});
</script>
<script>
//MODAL SCRIPT
$(function() {
$('.pop').on('click', function() {
$('.imagepreview').attr('src', $(this).find('img').attr('src'));
$('#imagemodal').modal('show');
});
});
</script>
pagination.php code:
$record_per_page = 18;
$page = ''; //store current page number
$output = '';
//check if page variable is present
if (isset($_POST["page"])) {
//ajax function
$page = $_POST["page"];
} else {
$page = 1;
}
$start_from = ($page - 1) * $record_per_page;
$query = "SELECT * FROM gallery ORDER BY id DESC LIMIT $start_from, $record_per_page";
$result = mysqli_query($conn, $query);
while ($row = mysqli_fetch_array($result)) {
$img = $row["path"];
$uploadDate = $row["uploadDate"];
$img = "<img id='modalImg' src='useruploads/" . $row['path'] . "' style='max-width: 100%; height: auto;'/>";
$output .= "
<div class='col-md-4 mainGalleryImg'>
<div class='myImg'>
<div class='pop'>
$img
</div>
<br>
</div>
</div>
";
}
$output .= "<div class='col-md-12' align='center'> <nav aria-label='Page navigation example'>
<ul class='pagination justify-content-center'> <li class='page-item'>
<a class='page-link' href='#' aria-label='Previous'>
<span aria-hidden='true'>«</span>
<span class='sr-only'>Previous</span>
</a>
</li>";
$page_query = "SELECT * FROM gallery ORDER BY id DESC";
$page_result = mysqli_query($conn, $page_query);
$total_records = mysqli_num_rows($page_result);
$total_pages = ceil($total_records/$record_per_page);
for ($i=1; $i <=$total_pages; $i++) {
$output .="<span class='pagination_link page-link' style='cursor:pointer;' id='".$i."'>".$i."</span>";
}
$output .= " <li class='page-item'>
<a class='page-link' href='#' aria-label='Next'>
<span aria-hidden='true'>»</span>
<span class='sr-only'>Next</span>
</a>
</li></ul>
</nav> </div>";
echo $output;
Bootstrap version: 4.4.1
jQuery version: https://ajax.googleapis.com/ajax/libs/jquery/3.4.1/jquery.min.js
$('.pop').on('click', function() { only attaches the handler to elements currently in DOM. Since you call it before you even retrieved the images it does nothing.
You need to use delegated event handlers.
$(document).on('click', '.pop', function() {

Clear an automatic Setinterval to open a modal

I have a list update part in my php where the ajax will update the list. The list is generated through sql queries and in a while loop. So it creates n number of list based on database values. Now I have a button on every list which will open up a modal box.
The update is done through set interval function below
var int = startinterval();
function startinterval() {
interval = setInterval(fetch_list, 1000);
return interval;
}
function fetch_list() {
var action = "fetch_data";
$.ajax({
url: "list.php",
method: "POST",
data: {
action: action
},
success: function(data) {
$('.list').html(data);
}
})
}
My Html where the data is updated to the list class
<div class="col-lg-12 list" style="overflow-y: auto;height: 400px;">
Now my problem is when i click the button on the list (as mention earlier) which should normally open up the modal box. Due to setInterval constantly updating the list every sec, the modal when open dissapears and goes hidden.
So what I'm trying is when I click the button to open the modal, it should stop the setinterval function. The setinterval should come back running once I click the cancel button inside the modal.
I tried many ways to clearinterval(), but no success. So expecting someone's help for me to get the wheels rolling.
Thanks in advance.
UPDATE:
my list would look like the below screenshot.
My list.php
if($_POST["action"] == "fetch_data")
{
echo fetch_list($connect);
}
function fetch_list($connect)
{
if(!$_SESSION['id']){
$output = '<ul class="list-unstyled"><h4>Please Select a Programme</h4></ul>';
return $output;
}else{
$query = "
SELECT * FROM list_programme
WHERE pid = '".$_SESSION['id']."'
ORDER BY pid ASC
";
$statement = $connect->prepare($query);
$statement->execute();
$result = $statement->fetchAll();
$output = '<ul class="list-unstyled">';
foreach($result as $row)
{
if($row["user"] == $_SESSION["uid"])
{
if($row["pstatus"] == '2')
{
$tickstatus = 'color:white';
$pcontrol = 'bg-success';
$pname = $row["pname"];
$border = 'border-color:#999;';
$pid = $row['pid'];
$notification = 'incomplete';
}
else
{
$pname = $row["pname"];
$pid = $row['pid'];
$notification = 'complete';
}
}
else
{
}
$output .= '
<div class="x_panel">
<button class="btn btn-round button-pcontrol '.$pcontrol.'" id="'.$pid.'" value="'.mb_strimwidth($pname, 0, 21, "...").'" data-notification="'.$notification.'" onClick="markcheck(this.id,this.value,this.dataset.notification)" style="'.$border.'"><i class="material-icons" title="Mark Completed" style="'.$tickstatus.'">check</i></button><span class="pname">'.$pname.'</span>
<span class="pcontrolbuttons">
<button class="btn btn-round button-pcontrol" id="programme" onClick="stopinterval()" data-id="'.$pid.'" data-toggle="modal" data-target="#programme'.$pid.'"><i class="material-icons" title="Assign users">person_add</i></button>
<button class="btn btn-round button-taskcontrol" data-id="'.$pid.'" data-value="'.mb_strimwidth($pname, 0, 21, "...").'" onClick="deleteprgm(this.dataset.id,this.dataset.value)"><i class="material-icons" title="Delete Task">delete</i></button>
</span>
</div>
<!--Modal -->
<div id="programme'.$id.'" class="modal custom-modal fade" role="dialog">
<div class="modal-dialog modal-dialog-centered" role="document">
<div class="modal-content">
<div class="modal-header">
<h5 class="modal-title text-center">Add to this programme</h5>
<button type="button" class="close" data-dismiss="modal" aria-label="Close">
<span aria-hidden="true">×</span>
</button>
</div>
<div class="modal-body">
Some Input elements, Drop downs, etc.,
</div>
<div class="submit-section">
<button type="button" class="btn btn-success submit-btn" id="addnusers"><i class="glyphicon glyphicon-plus"></i> Add Users</button>
<button type="button" class="btn btn-primary submit-btn" id="closeassignee" data-dismiss="modal"><i class="glyphicon glyphicon-remove"></i> Close</button>
</div>
</div>
</div>
</div>
</div>
<!-- /Modal -->';
}
$output .= '</ul>';
return $output;
}
}
So what I'm trying is when I click the button to open the modal, it
should stop the setinterval function.
You always should stops the functions execution, otherwise it will call the AJAX once per second and change the content of the modal.
document.getElementById('#button').addEventListener('click', function(event) {
event.preventDefault();
clearInterval(int);
// open modal
});
The setinterval should come back running once I click the cancel
button inside the modal.
document.getElementById('#cancel').addEventListener('click', function(event) {
event.preventDefault();
startinterval();
});
After searching for many resources, I had no luck to fix my issues with SetInterval.
So instead I modified my code to use setTimeout function. And the main drawback is this will not do live updates but once some button are clicked to modify the contents, the ajax success will call the setTimeout function and my list will be updated. So for time being the purpose is served.
Thanks for all the response.
Below is the single piece of code I Modified instead of a setInterval function
setTimeout(fetch_list, 1000);

Show database on bootstrap modal with Ajax in Laravel

I'm new at Laravel and ajax, I want to show database from mysql to Bootstrap modal, follow this
I use Laravel framework, this is the table
<tbody>
<?php
$result = DB::select('SELECT * FROM thongtinlodat');
foreach ($result as $key) {
echo '<tr>';
echo '<td>'.$key->TenNhaDauTu.'</td>';
echo '<td>'.$key->SoNhaDauTu.'</td>';
echo '<td>'.$key->NgayCapNDT.'</td>';
echo '<td>'.$key->NoiCapNDT.'</td>';
echo '<td>
<a class="btn btn-small btn-primary"
data-toggle="modal"
data-target="#exampleModal"
id="getUser"
data-whatever="'.$key->ID.' ">VIEW</a>
</td>';
echo '</tr>';
}
?>
</tbody>
Modal
<!-- Modal -->
<div class="modal fade" id="exampleModal" tabindex="-1" role="dialog" aria-labelledby="memberModalLabel" 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="memberModalLabel">View info</h4>
</div>
<div class="dash">
<!-- Content goes in here -->
</div>
</div>
</div>
</div>
This is javascript with ajax
$('#exampleModal').on('show.bs.modal', function (event) {
var button = $(event.relatedTarget); // Button that triggered the modal
var recipient = button.data('whatever'); // Extract info from data-* attributes
var modal = $(this);
var id = recipient;
var dataString = 'id=' + recipient;
$.ajax({
type: "GET",
url: "editdata",
data: dataString,
cache: true,
success: function (data) {
console.log(data);
modal.find('.dash').html(data);
},
error: function(err) {
console.log(err);
}
});
});
File editdata.php, get id from ajax and select data from mysql
<?php
$id = $_GET['id'];
$members = DB::table('thongtinlodat')
->where('ID', $id)
->first();
?>
In the routes, how can I get id to insert to the URL, like this Route::get('/editdata{?id=}', 'adminController#test');?
Thanks for helping!!!
In the routes, how can I get id to insert to the URL?
Like this:
Route::get('my/route/{arg1}', 'MyController#show')->where('arg1', '[0-9]+');
And in your controller:
public function show(arg1){...}
The "where" clause allows you to tell the route what to expect as an argument. For example in the lone above, the arg1 must be positive integer.
Looking at your code, I can only recommend you to look at laravel doc :). It's really well written and you will see how to improve your code.
More info: https://laravel.com/docs/5.6/routing#route-parameters

Passing data to Bootstrap 4 Modal

I'm using a PHP script to read data from a database and create an image gallery based on the results using Bootstrap Cards. Now I would like to have the possibility to delete data from the gallery. I finally found a way to do this -
PHP code:
[...]
echo "<div class='col-sm-4'>";
echo "<div class='card-deck'>";
echo "<div class='card' id='id_".$uploads[$i]['id']."'>";
echo "<img class='card-img-top' src='".$imagePath.$uploads[$i]['md5']."_tn.jpg' alt='Card image cap'>";
echo "<div class='card-img-overlay'><a class='close' href='#'>×</a></div>";
echo "<div class='card-body'>";
[...]
Javascript:
$(document).ready(function(){
$('.close').click(function(){
var target = $(this).parent().parent().attr('id');
$.ajax({url:'delete.php?id=' + target.replace('id_', '')});
location.reload();
});
});
This works perfectly fine, but I would like to include a Bootstrap Modal before actually deleting the picture from the gallery.
HTML modal code:
<div class="modal fade" id="deleteModal" tabindex="-1" role="dialog" aria-labelledby="exampleModalLabel" aria-hidden="true">
<div class="modal-dialog modal-dialog-centered" role="document">
<div class="modal-content">
<div class="modal-header">
<h5 class="modal-title" id="exampleModalLabel">Delete picture</h5>
<button type="button" class="close" data-dismiss="modal" aria-label="Close">
<span aria-hidden="true">×</span>
</button>
</div>
<div class="modal-body">Do you really want to delete this picture?</div>
<div class="modal-footer">
<button type="button" class="btn btn-secondary" data-dismiss="modal">Close</button>
<button type="button" id="deletePic" class="btn btn-danger">Delete Picture</button>
</div>
</div>
</div>
</div>
PHP code:
[...]
echo "<div class='col-sm-4'>";
echo "<div class='card-deck'>";
echo "<div class='card' id='id_".$uploads[$i]['id']."'>";
echo "<img class='card-img-top' src='".$imagePath.$uploads[$i]['md5']."_tn.jpg' alt='Card image cap'>";
echo "<div class='card-img-overlay'><a class='close' data-toggle='modal' data-target='#deleteModal' href='#'>×</a></div>";
echo "<div class='card-body'>";
[...]
Since the modal is now an additional step between the click on the X button and the actual delete my Javascript will not work anymore. Could someone please let me know how I can hand over the picture ID to the modal and in the next step delete the picture?
Thanks!
Simply you can do this:
$('a.close').click(function(){
var target = $(this).parent().parent().attr('id');
var pictureId = target.replace('id_', '');
$("#deletePic").data('picture-id', pictureId);
$("#deleteModal").modal("show");
});
Above code, we changed something. Firstly we removed ajax request. After that, we assigned picture id to delete button in the modal. After that, we opened the #deleteModal
Now, we know #deletePic has picture's ID number.
If we want to delete picture when clicked #deletePic button, we should use this:
$("#deletePic").on("click", function() {
var pictureId = $(this).data('picture-id');
$.ajax({url:'delete.php?id=' + pictureId});
});
And you shouldn't miss that, there are two .close class.
Firstly anchor has .close class that you want to use it. Also, bootstrap's modal contains .close class. So you should work ELEMENT.CLASSNAME if there are different elements has the same class.
I hope this will work for you.

dynamic php id JQuery ajax output will not change

After a button is selected on a fresh page, all information are there, but whenever another is clicked, the first info is still there and wont change until the page is refreshed.
Help me pass this will ya?
button
<?php while($b = mysqli_fetch_assoc($equery)): ?>
<button type="button" onclick="modal(<?=$b['id'];?>)" class="w3-btn w3-border" style="width: 260px; display: inline-block; margin: 9px">
<img src="">
<h3><?php echo $b['product'];?></h3>
<h5>Descritopm</h5>
<h6></h6>
</button>
<?php endwhile;?>
js:
function modal(id){
var data = {"id" : id};
jQuery.ajax({
url : <?=BASEURL;?>+'includes/modal.php',
method : "post",
data : data,
success: function(data){
jQuery('body').append(data);
jQuery('#mod').modal('show');
},
error: function(){
alert("IDK")
}
});
}
modal:
<?php
require_once '../core/init.php';
$id = $_POST['id'];
$id =(int)$id;
$sql = "SELECT * FROM aisle WHERE id = '$id'";
$result = $db->query($sql);
$product = mysqli_fetch_assoc($result);
?>
<!-- Modal -->
<?php ob_start();?>
<div id="mod" class="modal fade" role="dialog" tabindex="-1">
<div class="modal-dialog">
<!-- Modal content-->
<div class="modal-content">
<div class="modal-header">
<button type="button" class="close" data-dismiss="modal">×</button>
<h3 class="modal-title w3-center"><?=$product['product'];?></h3>
</div>
<div class="modal-body">
<p><?=$product['aisle'];?></p>
<p>$<?=$product['price'];?></p>
</div>
<div class="modal-footer">
<button type="button" class="btn btn-default" data-dismiss="modal">Close</button>
</div>
</div>
</div>
</div>
<?php echo ob_get_clean();?>
The problem is here
jQuery('body').append(data);
This line will append more modal and many modals will appear on your page. You should follow this way. Create a div tag called contents_from_ajax inside body tag and then use this.
jQuery('#contents_from_ajax').html(data);
This code will remove all old modals and create a new one instead of append, and then it will work fine.
Hope this help

Categories

Resources