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

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() {

Related

Gallery slider dont show in modal

using ACF PRO to created a field with a gallery, which should be displayed with other dynamic content in the modal when clicking on the post, the text content is displayed but the gallery not show, or show from the first post in cycle
The code that displays the loop on the page
//post query
$query = new WP_Query( $query_args );
ob_start();
// Wrap with a div when infinity load
echo ( $pagination_type == 'load_more' ) ? '<div class="postgrid-wrapper">' : '';
// Start posts query
if( $query->have_posts() ): ?>
<div class="<?php echo esc_attr( "post_grid col-3 layout_{$args['layout']} {$args['animation']} " ); ?>">
<?php while( $query->have_posts()): $query->the_post(); ?>
<?php if($args['layout'] == "1"){ ?>
<div class="grid_col" >
<div data-id="<?php the_ID(); ?>" class="single_grid view-post"><div class="more-button"><p>show more</p></div>
<div class="thumb">
<?php the_post_thumbnail('full'); ?>
</div>
<div class="cont">
<h2 class="title"><?php echo get_the_title(); ?></h2></a>
<div class="subtitle"><?php the_field('subtitle'); ?></div>
</div>
</div>
</div>
<?php } else if( $args['layout'] == 2 ){ ?>
<?php } ?>
<?php endwhile; ?>
</div>
Modal using ajax to show dynamic content (functions.php)
function load_post_by_ajax_callback() {
check_ajax_referer('view_post', 'security');
$args = array(
'post_type' => 'post',
'p' => $_POST['id'],
);
$portfolios = new WP_Query( $args );
$arr_response = array();
if ($myposts->have_posts()) {
while($myposts->have_posts()) {
$myposts->the_post();
//
$arr_response = array(
'title' => get_field('acf-field-title'),
'subtitle' => get_field('acf-field-subtitle'),
'content' => get_field('acf-field-content'),
'autor' => get_field('acf-field-autor'),
'thumb' => get_the_post_thumbnail(),
'slider' => get_field('gallery'),
);
}
wp_reset_postdata();
}
echo json_encode($arr_response);
wp_die();
}
add_action('wp_ajax_load_post_by_ajax', 'load_post_by_ajax_callback');
add_action('wp_ajax_nopriv_load_post_by_ajax', 'load_post_by_ajax_callback');
Script parsing content from the post and show content in modal with the assigned id from acf field
jQuery(function($) {
$('body').on('click', '.view-post', function() {
var data = {
'action': 'load_post_by_ajax',
'id': $(this).data('id'),
'security': blog.security
};
$.post(blog.ajaxurl, data, function(response) {
response = JSON.parse(response);
$('#postModal .modal-body #postModalTilte').text(response.title);
$('#postModal .modal-body #postModalSubtitle').html(response.subtitle);
$('#postModal .modal-body #postModalContent').html(response.content);
$('#postModal .modal-body #postModalAutor').html(response.autor);
$('#postModal .modal-body #postModalSlider').html(response.slider);
var postModal = new bootstrap.Modal(document.getElementById('postModal'));
postModal.show();
});
});
Bootstrap modal code
<div class="modal" id="postModal">
<div class="modal-dialog modal-dialog-centered" style="max-width:70%">
<div class="modal-content">
<div class="modal-body">
<button type="button" class="btn-close" data-bs-dismiss="modal" aria-label="Close" style="float:right;border:none;"></button>
<div class="row">
<div class="col-left">
<div class="grid-gallery" id="postModalSlider"></div>
</div>
<div class="col-right">
<h5 class="portfolio-title" id="postModalTitle">Title: </h5>
<p class="portfolio-customer" id="postModalSubtitle">Subtitle: </p>
<p class="portfolio-review" id="postModalContent">Content</p>
<p class="portfolio-price" id="postModalAutor">Autor: </p>
</div>
</div>
</div>
</div>
</div>
</div>
I tried to paste in modal, the example gallery from the ACF documentation, in this case they are shown only from the very first post and the necessary not show.
I understand that the script cannot parse the necessary gallery data from the post, but I don't know how to fix it

Change change background image by clicking a div

I have an accordion style div with 3 boxes. When clicking it is opening and closing the content into view. I have an absolute positioned div with a background image behind that I need changed on each click. When I first load the page I am able to get it to work as you click each element. However, once you click any of those div boxes again it sticks to the same background image and won't cycle through. I have tried using .next(), .closest() but not working.
<?php
$args = array(
'post_type' => 'services',
's' => '-demand' // will exclude all post with the title name "Demand" present
);
$services = new WP_Query($args);
;?>
<?php if($services->have_posts()) : ?>
<section class="section__wrapper" id="services__set">
<div class="services__accordion" id="class-accordions">
<div class="services__container">
<?php $i = 1;
while($services->have_posts()): $services->the_post();
global $post;
$post_slug = $post->post_name; ?>
<div class="services__col" id="<?php echo $post_slug;?>">
<span class="h2 services__title"><?php the_title();?></span>
<div class="services__content">
<?php $barreDesc = get_field('class_description'); if($barreDesc): ?><p><?php echo $barreDesc; ?></p><?php endif; ?>
<div class="services__btn">
<a class="btn white-btn" href="<?php echo site_url(); ?>/locations/">Find A Studio</a>
</div>
</div>
</div>
<div class="services_bg" style="background-image:url(<?php the_field('service_feature_image');?>);"></div>
<?php $i++; endwhile;wp_reset_postdata();?>
</div>
</div>
</section>
<script>
jQuery(document).ready(function($) {
$('.services__content').css('height', '0');
$('.services__col').first().addClass("active-reveal");
$('.services_bg').first().addClass("active");
$('.services__col').click(
function() { //When you click on a button...
var isActive = $(this).hasClass('active-reveal');
if( isActive ){ //If it already has an active class...
$(this).removeClass('active-reveal'); //...it loses the active class....
}
else{ //If it does NOT already have an active class...
$('.services__col').removeClass('active-reveal'); //all buttons lose the active class...
$(this).addClass('active-reveal'); //...except this one.
}
if ($('.services__col').attr("class") == "active-reveal") {
$(this).next('.services_bg').removeClass('active');
} else {
$(this).next('.services_bg').addClass('active');
}
});
});
</script>
<?php endif;?>
Updated code with answer
<?php
$args = array(
'post_type' => 'services',
's' => '-demand' // will exclude all post with the title name "Demand" present
);
$services = new WP_Query($args);
;?>
<?php if($services->have_posts()) : ?>
<section id="services__set">
<div class="services__accordion" id="class-accordions">
<div class="services__container">
<?php $i = 1;
while($services->have_posts()): $services->the_post();
global $post;
$post_slug = $post->post_name; ?>
<div class="services__col" id="<?php echo $post_slug;?>">
<span class="h2 services__title"><?php the_title();?></span>
<div class="services__content">
<?php $barreDesc = get_field('class_description'); if($barreDesc): ?><p><?php echo $barreDesc; ?></p><?php endif; ?>
<div class="services__btn">
<a class="btn white-btn" href="<?php echo site_url(); ?>/locations/">Find A Studio</a>
</div>
</div>
</div>
<div class="services_bg" style="background-image:url(<?php the_field('service_feature_image');?>);"></div>
<?php $i++; endwhile;wp_reset_postdata();?>
</div>
</div>
</section>
<script>
jQuery(document).ready(function($) {
$('.services__content').css('height', '0');
$('.services__col').first().addClass("active-reveal");
$('.services_bg').first().addClass("active");
$('.services__col').click(
function() { //When you click on a button...
var isActive = $(this).hasClass('active-reveal');
if( isActive ){ //If it already has an active class...
$(this).removeClass('active-reveal'); //...it loses the active class....
}
else{ //If it does NOT already have an active class...
$('.services__col').removeClass('active-reveal'); //all buttons lose the active class...
$(this).addClass('active-reveal'); //...except this one.
}
if ($('.services__col').attr("class") == "active-reveal") {
$(this).next('.services_bg').removeClass('active');
} else {
$('.services_bg').removeClass('active');
$(this).next('.services_bg').addClass('active');
}
});
});
</script>
<?php endif;?>

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

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});
});
});
});

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

Send value from jquery to php

I have a web page that displays several albums and the following html code for an album icon that should allow the user to change the access settings to the specific album ($row holds the response values from a db query that returns info on albums)
<a data-title="'.$row['title'].'" data-description="'.$row['description'].'" data-id="'.$row['photoCollectionId'].'" class="open-update_dialog2" data-toggle="modal" href="#update_dialog2">
<i class="ace-icon fa fa-eye"></i>
</a>
and if the user clicks on it, a modal shows up
<div class="modal fade" id="update_dialog2" role="dialog">
<div class="modal-dialog">
<div class="modal-content">
<ul id="check-list-box" class="list-group checked-list-box">
<?php
foreach (getFriends($email) as $row) {
$flag = checkAccessRights($row['email'],1)['value'];
echo '<li class="list-group-item" data-checked='.$flag.'>'.$row['firstName'].' '.$row['lastName'].'</li>';
}
?>
</ul>
</div>
</div>
</div>
.js
$(document).on("click", ".open-update_dialog2", function () {
albumName = $(this).data('title');
$(".modal-body #albumName").val(albumName);
albumDescription = $(this).data('description');
$(".modal-body #albumDescription").val(albumDescription);
albumId = $(this).data('id');
});
My problem is that each modal would need to fetch different data depending on the album the user clicked on and thus I want to replace the value of 1 in checkAccessRights($row['email'],1) with the value of the variable albumName.
Is there a way to get the value from jquery to php? Any tip would be greatly appreciated!
You can use ajax,
This (Ajax) help you to create dynamic album.
JQuery it is a client side, PHP it is a server. So you should send request to the server with albumId parameter.
$(document).on("click", ".open-update_dialog2", function () {
albumName = $(this).data('title');
$(".modal-body #albumName").val(albumName);
albumDescription = $(this).data('description');
$(".modal-body #albumDescription").val(albumDescription);
albumId = $(this).data('id');
$.get("yourPhpFile.php", {albumId:albumId}).done(function(resp) {
//
});
});
and on your server you need get this parameter and put in your loop
<div class="modal fade" id="update_dialog2" role="dialog">
<div class="modal-dialog">
<div class="modal-content">
<ul id="check-list-box" class="list-group checked-list-box">
<?php
$albumId = $_GET['albumId'] ? $_GET['albumId'] : 1;
foreach (getFriends($email) as $row) {
$flag = checkAccessRights($row['email'], $albumId)['value'];
echo '<li class="list-group-item" data-checked='.$flag.'>'.$row['firstName'].' '.$row['lastName'].'</li>';
}
?>
</ul>
</div>
</div>

Categories

Resources