I need help i want to download the htmlf 5 canvas for each individuall and im calling the image data dynamic but not been able to download the canvas plzz help me out from such informartion through my code in future user may add as many template images it will be called with same design as i have called data dynamically so im not getting what to do for download the canvas for such div images can anyone help me out
if ($sImage)
{
$gallery = get_field('field_5ea2b74754193');
?>
<div class="row">
<?php
$counter=1;
$canvas=1;
foreach ($gallery as $value) { ?>
<div class="col-sm-4">
<div class="onethird">
<center>
<h2>Design-<?php echo $counter++;?></h2><br>
<div class="my_banner" id="myCanvas <?php echo $canvas; ?>">
<div class="template_bg" style="background-image: url(<?php echo $sImage?>);">
<!--php echo '<img src="'.$sImage.'" class="absolute img-fluid" />'; ?-->
<img src="<?php echo $value['full_image_url'];?>" class="relative img-fluid" />
</div>
</div>
<div>
<br>
<a id="download" href="#" class="dowload btn btn-danger">Download</a>
</div>
</center>
</div>
</div>
<?php $canvas++; } ?>
<script>
$(document).ready(function() {
var canvas_id=0;
$('a.dowload').click(function(e){
e.preventDefault();
alert('Download on process');
html2canvas($('#myCanvas'),{
onrendered: function (canvas) {
var a = document.createElement('a');
a.href = canvas.toDataURL("image/png");
alert(a.href);
a.download = 'my-image.png';
a.click();
}
});
});
});
</script>
</div>
</div>
<?php
}
I have used a modal box for my issue to get the work to be done in proper work for converting Div images to html2canvas to create one image and download the image side by side
if ($sImage)
{
$gallery = get_field('field_5ea2b74754193');
?>
<div class="row">
<?php
$counter=1;
foreach ($gallery as $key=> $value) {?>
<div class="col-sm-4">
<div class="onethird">
<center>
<h2>Design-<?php echo $counter++;?></h2><br>
<div class="my_banner" id="myCanvas_<?php echo $value['id']; ?>">
<div class="template_bg" style="background-image: url(<?php echo $sImage?>);">
<img src="<?php echo $value['full_image_url'];?>" class="relative img-fluid" />
</div>
</div>
<div>
<br>
<!-- Preview -->
<div class="qrcimg mt-3" data-toggle="modal" data-target="#myModal">
<input id="preview_box" type="button" data-id="<?php echo $value['id'];?>" name="canvas_id" value="Get Image" class="preview_box btn btn-outline-primary"/>
</div>
<div class="modal fade" id="myModal" role="dialog">
<div class="modal-dialog">
<!-- Modal content-->
<div class="modal-content">
<div class="modal-header">
<h4 class="modal-title text-center" style="color:black; font-weight:bold;">SlashDP</h4>
<button type="button" class="close" data-dismiss="modal" style="font-size:2rem;">×</button>
</div>
<div class="modal-body">
<div id="canvas_image" data-id="<?php echo $value['id'];?>"></div>
<center><a id="download" href="#" class="clear btn btn-danger"><i class="fa fa-download" style="font-size:1rem;"> Download</i></a></center>
</div>
</div>
</div>
</div>
</div>
</center>
</div>
</div>
<?php } ?>
<!-- Canvas image get preview and download code -->
<script>
$(document).ready(function() {
// Global variable
var getCanvas;
$(".preview_box").on('click', function() {
var dataId = $(this).attr("data-id");
var canvas_img = $("#myCanvas_"+dataId).get(0);
html2canvas(canvas_img,{
useCORS: true,
allowTaint: false,
letterRendering: true,
logging:true,
onrendered: function(canvas) {
$("#canvas_image").append(canvas);
getCanvas = canvas;
console.log(canvas);
}
});
});
$("#download").on('click', function() {
var imageData =getCanvas.toDataURL("image/png");
// Now browser starts downloading
// it instead of just showing it
var newData = imageData.replace(/^data:image\/png/, "data:application/octet-stream");
$("#download").attr("download", "my-demo.png").attr("href", newData);
});
jQuery(".clear").click(function(){ jQuery("#canvas_image").empty();});
jQuery(".close").click(function(){ jQuery("#canvas_image").empty();});
});
</script>
</div>
</div>**
Related
So I have succeeded in passing the variables from one modal to another.The problem is they are multiple variables and I am looping them with the PHP foreach function, all the items are displayed but when I click on any item only the first variable is passed and not the specific one I chose. How do I fix this
here is the code for the initial modal
<div class="modal fade bs-modal-md" id="cardmodal" tabindex="-1" role="dialog" aria-
labelledby="mySmallModalLabel" aria-hidden="true">
<div class="modal-dialog modal-md">
<div class="modal-content">
<div class="modal-header">
<h5 class="modal-title" id="exampleModalLongTitle">SELECT A CARD</h5>
<button type="button" class="close" data-dismiss="modal" aria-label="Close">
<span aria-hidden="true">×</span>
</button>
</div>
<div class="modal-body">
<div class="mini-carousel">
<ul class="mini-item">
<?php
$cards = $card->load_category('WOMEN','WR');
$category_products=$cards['category_products'];
$num_rows = count($category_products);
if ($num_rows < 1) {
echo '<div class="info">We shall update you when this is back in Stock</div>';
?>
<a onClick="pageModel(this);" href="javascript:void(0);" id="<?php echo
site_url('home/getview/contact_form/'.$categorynameID); ?>" >Click here to submit your
contact to be updated</a>
<?php
} else {
foreach($category_products as $cp)
{
$status = $cp["status"];
$product_quantity = $cp["quantity"];
$notify_quantity = $cp["reorder_level"];
$images = $this->home_m->get_product_images($cp['inventory_id'],true);
if($images){
$image = $images[0];
$image_name = $image["thumb"].'.'. $image["extension"];
$image_source = $image['source'];
$check_pic = DEFAULT_UPLOAD.'/'.$image_source.'/'.$image_name;
$product_image = $image_name;
}else{
$product_image = '';
}
?>
<li class="product-item col-xs-12 col-sm-4 col-md-3">
<div class="product-inner">
<div class="product-thumb has-back-image zoom">
<a id="testd" data-id="<?php echo base_url($check_pic); ?>" data-
dismiss="modal" data-toggle="modal" onclick="addModalDetails()" href="#single_card_view">
<? php
if(($product_image != "") || (($product_image != NULL))) {
if (file_exists($check_pic)) { ?>
<img id="cardimage" src="<?php echo base_url($check_pic); ?>" alt="Product Image" ></img>
<?php } else {
echo "<img class=\"img-fluid\"
src=\"http://geestar.co.tz/images/category/product.png\" alt=\"Product Image\" />";
}
} else {
echo "<img class=\"img-fluid\" src=\"http://geestar.co.tz/images/category/product.png\"
alt=\"Product Image\" />";
}
?>
</a>
</div>
<div class="product-info">
<h6 id="cardname" class="product-name"><?=$cp["product_name"];?></a>
</h6>
<span class="price">
<ins id="cardprice">TZS <?=number_format($cp["selling_price"]);?
>
</ins>
</span>
</div>
</div>
</li>
<?php
}
}
?>
this is the JS Code where i pass the values to the other modal
function addModalDetails(){
var name = $('#cardname').html();
var image= $('#cardimage').html();
var price =$('#cardprice').html();
$('#heading').html(name);
$('#cost').html(price);
var imgsrc = $('#testd').data('id');
$('#picture').attr('src',imgsrc);
}
And this is the code of the modal where i want the data to be passed
<div class="modal fade product_view" id="single_card_view">
<div class="modal-dialog">
<div class="modal-content">
<div class="modal-header">
<a href="#" data-dismiss="modal" class="class pull-right"><span class="glyphicon
glyphicon-remove"></span></a>
<h3 id="heading" class="modal-title"></h3>
</div>
<div class="modal-body">
<div class="row">
<div class="col-md-6 product_img">
<img id="picture" src="" class="img-responsive">
</div>
<div class="col-md-6 product_content">
<p> <input id="gift_message" class="form-control" rows="5" placeholder="<?
php _l('Gift Message'); ?>" name="gift_message" > </input></p>
<h3 id="cost" class="cost"></span>TZS
<? =number_format($cp["selling_price"]);?></h3>
<div class="row">
<!-- end col -->
<!-- end col -->
<!-- end col -->
</div>
<div class="space-ten"></div>
<div class="btn-ground">
<button type="button" class="button" data-dismiss="modal"
onClick="addCardDetails()"> Add Card</button>
</div>
</div>
</div>
</div>
</div>
</div>
</div>
You're currently using a foreach loop to assign the same ID to multiple html tags. For simplicity of this answer, I will be taking your <img> tag with the ID cardimage as example. Furthermore I'd like to note that your ID's should always be unique!
The problem
<img id="cardimage" src="<?php echo base_url($check_pic); ?>" alt="Product Image"></img>
Every team you're looping through the $category_products array, you're adding another one of those tags, identical to the last one.
For example if you loop 3 times through the $category_products array, you will get 3 times the same ID.
<img id="cardimage" src="<?php echo base_url($check_pic); ?>" alt="Product Image"></img>
<img id="cardimage" src="<?php echo base_url($check_pic); ?>" alt="Product Image"></img>
<img id="cardimage" src="<?php echo base_url($check_pic); ?>" alt="Product Image"></img>
When there are multiple identical ID's on a webpage, your javascript will pick the first one it can find, and run your script on that, as it only expects one result. To fix this, you should make all your ID's unique.
A possible solution
First of all, make all of your ID attributes unique. In your loop you're looping through $category_products as $cp, and you appearantly have the variable $cp['inventory_id']. I'll be taking that as unique id for this answer for now.
You could append this unique ID behind your ID like this:
foreach($category_products as $cp) { ?>
<img id="cardimage-<?=$cp['inventory_id']?>" src="<?php echo base_url($check_pic); ?>" alt="Product Image"></img>
<?php }
Then change your addModalDetails() like this:
function addModalDetails(id){
var name = $('#cardname-'+id).html();
var image= $('#cardimage-'+id).html();
var price =$('#cardprice-'+id).html();
$('#heading-'+id).html(name);
$('#cost-'+id).html(price);
var imgsrc = $('#testd-'+id).data('id');
$('#picture-'+id).attr('src',imgsrc);
}
and call it like this:
addModalDetails(<?=$cp['inventory_id']?>);
I am using this jquery script within a php to add a unique id onto each looping modal.
thing is everything works perfectly well except I can't get why the $count for var myVideo=document.getElementById('htmlVideo' + <?php echo $count?>); returns a at say 6 all the time
So lets say I were to click on videoBtn1, #videoModal1 will open up with the right video but myVideo will return me the video from #htmlVideo6.
regardless if I were to click on videoBtn1 or videoBtn10, myVideo is always pointing at #htmlVideo6
<?php
$count = 0;
while ( have_rows('video') ) : the_row(); ?>
<div class="col-lg-4 col-md-6 mt-3 mt-lg-5">
<div class="d-flex flex-column h-100 px-3">
<div data-toggle="modal" data-target="#videoModal<?php echo $count?>" id="videoBtn<?php echo $count?>">
<img src="<?php echo get_sub_field('video_thumbnail') ?> " width="100%" style="height: 240px;object-fit: cover;">
</div>
<div class="py-3 h-100 d-flex flex-column align-items-start">
<h4 class="text-heavy">
<?php echo get_sub_field('title') ?>
</h4>
<p>
<?php echo get_sub_field('content') ?>
</p>
</div>
</div>
</div>
<!--Video Modal -->
<div class="modal fade" id="videoModal<?php echo $count?>" role="dialog" aria-labelledby="videoModal<?php echo $count?>Label" aria-hidden="true" >
<div class="modal-dialog modal-lg" role="document">
<div class="modal-content">
<div class="modal-body p-3 position-relative">
<div type="button" class="close" data-dismiss="modal" aria-label="Close">
<span aria-hidden="true" class="text-white">×</span>
</div>
<video id="htmlVideo<?php echo $count?>" width="100%" controls style="z-index:5">
<source src="<?php echo get_sub_field('video')?>" type="video/mp4">
</video>
<script>
var container = $("#htmlVideo<?php echo $count?>");
var myVideo=document.getElementById('htmlVideo' + <?php echo $count?>);
$(document).ready(function(){
$("#videoBtn<?php echo $count?>").click(function(){
console.log(myVideo);
myVideo.play();
});
$("#videoModal<?php echo $count?>").click(function(e)
{
// if the target of the click isn't the container nor a descendant of the container
if (!container.is(e.target) && container.has(e.target).length === 0)
{
myVideo.pause();
}
});
});
</script>
</div>
</div>
</div>
</div>
<?php
$count++;
endwhile;
?>
It is very poor practice to loop a script. Give the button and/or video a class and use the class to access it using ONE piece of script - that means you do not even need to give it an ID
This is overwriting ALL OTHER vars every time
var myVideo=document.getElementById('htmlVideo' + <?php echo $count?>);
Try this:
Give the parent container a class:
<div class="modalClickParent col-lg-4 col-md-6 mt-3 mt-lg-5">
and use something like
$(function() {
$("[data-toggle=modal]").on("click", function() {
const myVideo = $(this).closest(".modalClickParent").next().find("video").get(0);
if (!$(this).data("playing")) {
myVideo.play();
$(this).data("playing", true);
} else {
myVideo.pause();
$(this).data("playing", false);
}
});
});
Just create a class on which you want to click and give it a data-id attribute
In jquery section use code like
$('.class').click(function(){<bR>
var that=$(this);<bR>
var id=that.data('id');<bR>
//now do your stuff here like<bR>
$('#div'+id).modal('show');<bR>
});
I have a button inside a loop.
When the user clicks on the button I want to create a $_SESSION variable with the value of a variable inside the loop.
For example, the variable $id_puja is 767 at this loop item, when the user clicks on the button I want to create the session variable $_SESSION['clicked_puja'] = $row['id_puja'].
This is the button:
while{...
$id_puja = $row['id_puja'];
...
<button type="button" class="btn btn-info btn-lg" data-toggle="modal" data-target="#myModal">Open Modal</button>
...
}
I
EDITED, full loop code:
<?php
$resultadopujas=0;
global $mysqli;
$loop = mysqli_query($mysqli, "SELECT * FROM tb_pujas
WHERE subasta_puja = '".$subasta."'")
or die (mysqli_error($mysqli));
$orden = 0;
$resultado = $loop ->num_rows;
if ($resultado == 0){
?> <div class="container">
<div class="jumbotron">
<div class="row">
<div class="col-md-6">
<p><?php echo $resultado."NO HAY PUJAS"?></p>
</div>
</div>
</div>
</div>
<?php
}
$numpuja=0;
while ($row = mysqli_fetch_array($loop))
{$numpuja = $numpuja+1;
$originalDate = $row['datetime_puja'];
$newDate = date("d-m-Y H:i:s",strtotime($originalDate))
?>
<div class="container">
<div class="jumbotron" style="background-color: white">
<div class="row">
<div class="col-md-2">
<img style="width: 80px;height: auto;align-self: " src="garantia.png">
</div>
<div class="col-md-2">
<img style="width: 80px;height: auto;align-self: " src="ok.png">
</div>
<div class="col-md-2">
<img style="width: 80px;height: auto;align-self: " src="extra.png">
</div>
<div class="col-md-2">
<p><strong>Dia/Hora puja: </strong><?php echo $newDate?></p>
</div>
<div class="col-md-2">
<p><strong>Precio puja: </strong><?php echo $row['precio_puja']." €"?></p>
</div>
<div class="col-md-2">
<p><?php echo "<strong>Puja núm:</strong> ".$numpuja?></p>
</div>
</div>
<div class="row">
<div class="col-md-12">
<p><?php echo "<strong>Comentarios:</strong> ".$row['comentarios_puja']?></p>
</div>
</div>
<div class="row">
<div class="col-md-4">
<img style="width: 100%;height: auto;align-self: " src="https://cribbeo.com/pujas/<?php echo $row['foto1']?>">
</div>
<div class="col-md-4">
<img style="width: 100%;height: auto;align-self: " src="https://cribbeo.com/pujas/<?php echo $row['foto2']?>">
</div>
<div class="col-md-4">
<img style="width: 100%;height: auto;align-self: " src="https://cribbeo.com/pujas/<?php echo $row['foto3']?>">
</div>
</div>
<div class="row">
<div class="col-md-4">
</div>
<div class="col-md-4">
</div>
<div class="col-md-4">
<script>
function myclick(){
alert (<?php echo $row['precio_puja']?>);
}
</script>
<button type="button" class="btn btn-info btn-lg" data-toggle="modal" id="boton" onclick="myclick()" data-target="#myModal">Open Modal</button>
</div>
</div>
</div>
</div>
</div>
<?php
}
?>
EDITED modal part
<div id="myModal" class="modal fade" role="dialog">
<div class="modal-dialog">
<!-- Modal content-->
<div class="modal-content">
<div class="modal-header">
<button type="button" class="close" data-dismiss="modal">×</button>
<h4 class="modal-title">Mensajes de la subasta <?php echo $referencia."VAR=".$_COOKIE['puja']?></h4>
</div>
<div class="modal-body" style="background-color:#486A86; color: white">
<div class="container">
<header class="header">
<h1>Chat</h1>
</header>
<main>
<img src="images/logohorizontal.png" alt="Cribbeo" width="200px">
<div class="userSettings">
<label for="userName">Usuario: <?php echo $_SESSION['usuario']?></label>
<input id="userName" type="hidden" placeholder="Username" maxlength="32" value=" <?php echo $_SESSION['usuario']?>">
</div>
<div class="chat">
<div id="chatOutput"></div>
<input id="chatInput" type="text" style="background-color:white; color: #486A86" placeholder="Escribe aquí el texto de tu mensaje" maxlength="128">
<button id="chatSend" style="background-color:#486A86; color: white">Enviar</button>
</div>
</main>
</div>
</div>
<div class="modal-footer">
<button type="button" class="btn btn-default" data-dismiss="modal">Cerrar</button>
</div>
</div>
</div>
</div>
And this is chat.js
$(document).ready(function() {
var chatInterval = 250; //refresh interval in ms
var $userName = $("#userName");
var $chatOutput = $("#chatOutput");
var $chatInput = $("#chatInput");
var $chatSend = $("#chatSend");
function sendMessage() {
var userNameString = $userName.val();
var chatInputString = $chatInput.val();
$.get("./write.php", {
username: userNameString,
text: chatInputString
});
$userName.val("");
retrieveMessages();
}
function retrieveMessages() {
$.get("./read.php", function(data) {
$chatOutput.html(data); //Paste content into chat output
});
}
$chatSend.click(function() {
sendMessage();
});
setInterval(function() {
retrieveMessages();
}, chatInterval);
});
Try this-
//START OF LOOP...
//Add data-var attribute to your button to store the value of the session variable to be picked up by jQuery.
<button type="button" class="btn btn-info btn-lg session-btn" data-toggle="modal" data-target="#myModal" data-var="<?php echo $id_puja;?>">Open Modal</button>
//END OF LOOP..
// jQuery CDN link
<script src="https://code.jquery.com/jquery-3.3.1.min.js" integrity="sha256-FgpCb/KJQlLNfOu91ta32o/NMZxltwRo8QtmkMRdAu8=" crossorigin="anonymous"></script>
<script>
$('.session-btn').on('click', function(){
var session_var = $(this).data('var');
console.log(session_var); // prints the session variable value to the console.
$(document).ready(checkModal);
function checkModal() {
if($('#myModal').is(':visible')){
//if the modal is visible on the page
$.ajax({
url: 'read.php',
type: 'POST',
data: {session_var: session_var},
success: function(){
alert('success');
}
});
}
}
});
</script>
In read.php file
<?php
require("connect.php");
session_start():
//connect to db
$db = new mysqli($db_host,$db_user, $db_password, $db_name);
if ($db->connect_errno) {
//if the connection to the db failed
echo "Failed to connect to MySQL: (" . $db->connect_errno . ") " . $db->connect_error;
}
if(isset($_POST['session_var'])){
$_SESSION['session_var'] = $_POST['session_var'];
echo $_SESSION['session_var'];
$query="SELECT * FROM chat WHERE id_puja ='".$_SESSION['session_var']."' ORDER BY id ASC";
//execute query
if ($db->real_query($query)) {
//If the query was successful
$res = $db->use_result();
while ($row = $res->fetch_assoc()) {
$username=$row["username"];
$text=$row["text"];
$time=date('G:i', strtotime($row["time"])); //outputs date as # #Hour#:#Minute#
echo "<p>$time | $username: $text</p>\n";
}
}else{
//If the query was NOT successful
echo "An error occured";
echo $db->errno;
}
} else {
echo 'variable is not posted!';
}
$db->close();
?>
Have some db information that I'm trying to get into some modals.
Problem seems to be that the modal only ever grabs the variables from the last while loop. Does all the php on a page run first? Even when its not called?
So I know there is probably easier ways to do this using get_results() and fetch_array and fetch_row but those don't seem to work for me in php 5.5.
Also, I read somewhere to use AJAX. Well as I have never used ajax before, is this something I should look into?
<div class="col-md-4">
<?php
error_reporting(E_ALL);
ini_set('display_errors', 1);
require ($_SERVER['DOCUMENT_ROOT'].'/db-connect.php');
$conn = new mysqli($servername, $username, $password, $dbname);
if ($conn->connect_error) {
die("Connection failed: " . $conn->connect_error);
}
//echo $conn->host_info . "\n";
if ($stmt = $conn->prepare("SELECT time, title, tool, descript, thumbpath, smallpath, mediumpath, largepath FROM websites ORDER BY id DESC LIMIT 1")){
//$stmt->bind_param('s',$id);
$stmt->execute();
$stmt->store_result();
$stmt->bind_result($time, $title, $tool, $descript, $thumbpath, $smallpath, $mediumpath, $largepath);
while ($stmt->fetch()) {
}
$stmt->free_result();
$stmt->close();
}
$conn->close();
?>
<img class="img-responsive" title="<?php echo $tool; ?>" data-toggle="modal" data-target="#modalPort" sizes="100vw" src="<?php echo $thumbpath; ?>" srcset="<?php echo $smallpath; ?> 500w, <?php echo $mediumpath; ?> 1000w, <?php echo $largepath; ?> 1500w" alt="Portfolio Site">
<span class="time line-height-small"><?php echo $time; ?></span>
</div>
The variable's here work fine. The problem is that I'm running this same php script a few other times with the same bind_result variables. I don't really want to change variables for each modal.
Modal:
<!-- Website Modals-->
<div class="modal fade" id="modalPort" tabindex="-1" role="dialog" aria-labelledby="portfolioModallabel" aria-hidden="true">
<div class="modal-dialog">
<div class="modal-content">
<div class="modal-header">
<h4 class="modal-title" id="portfolioModallabel"><?php echo $title; ?></h4>
</div>
<div class="modal-body text-center">
<img class="img-responsive center-block" src="<?php echo $thumbpath; ?>" sizes="100vw" srcset="<?php echo $smallpath; ?> 500w, <?php echo $mediumpath; ?> 1000w, <?php echo $largepath; ?> 1500w" alt="Portfolio Site">
<p class="line-height-small"><?php echo $descript; ?></p>
</div>
<div class="modal-footer">
<button type="button" class="btn btn-default" data-dismiss="modal">Close</button>
</div>
</div>
</div>
One way is to put modal inside while ($stmt->fetch()) { } assign both modal trigger button and modal itself unique id
Note the data-target="#modalPort<?php echo $id;?>" in modal trigger button and id="modalPort<?php echo $id;?>" in modal HTML
<?php while ($stmt->fetch()) { ?>
<button data-toggle="modal" data-target="#modalPort<?php echo $id;?>" class="btn btn-default">Modal</button>
<div class="modal fade" id="modalPort<?php echo $id;?>" tabindex="-1" role="dialog" aria-labelledby="portfolioModallabel" aria-hidden="true">
<div class="modal-dialog">
<div class="modal-content">
<div class="modal-header">
<h4 class="modal-title" id="portfolioModallabel"><?php echo $title; ?></h4>
</div>
<div class="modal-body text-center">
<img class="img-responsive center-block" src="<?php echo $thumbpath; ?>" sizes="100vw" srcset="<?php echo $smallpath; ?> 500w, <?php echo $mediumpath; ?> 1000w, <?php echo $largepath; ?> 1500w" alt="Portfolio Site">
<p class="line-height-small"><?php echo $descript; ?></p>
</div>
<div class="modal-footer">
<button type="button" class="btn btn-default" data-dismiss="modal">Close</button>
</div>
</div>
</div>
</div>
<?php } ?>
Alternate If you want to do with ajax, put modal HTML outside the while loop, add <?php echo $id;?> as data attribute to modal trigger button data-id="<?php echo $id;?>"
<?php while ($stmt->fetch()) { ?>
<button data-toggle="modal" data-target="#modalPort" data-id="<?php echo $id;?>" class="btn btn-default">Modal</button>
<?php } ?>
Modal event listener to get the data attribute value and later use in Ajax method to get the respective row data to show in modal
$(document).ready(function(){
$('#modalPort').on('show.bs.modal', function (e) {
var dataid = $(e.relatedTarget).data('id');
var dataString = 'dataid=' + dataid;
$.ajax({
type: "POST",
url: "get_data.php",
data: dataString,
cache: false,
success: function(data){
$("#content").html(data);
}
});
});
});
get_data.php will be
<?php
//Include database connection
if($_POST['dataid']) {
//run query against `dataid`
?>
<div class="modal-header">
<h4 class="modal-title" id="portfolioModallabel"><?php echo $title; ?></h4>
</div>
<div class="modal-body text-center">
<img class="img-responsive center-block" src="<?php echo $thumbpath; ?>" sizes="100vw" srcset="<?php echo $smallpath; ?> 500w, <?php echo $mediumpath; ?> 1000w, <?php echo $largepath; ?> 1500w" alt="Portfolio Site">
<p class="line-height-small"><?php echo $descript; ?></p>
</div>
<div class="modal-footer">
<button type="button" class="btn btn-default" data-dismiss="modal">Close</button>
</div>
<?php } ?>
and Modal HTML will be (outside the loop)
<div class="modal fade" id="modalPort" tabindex="-1" role="dialog" aria-labelledby="portfolioModallabel" aria-hidden="true">
<div class="modal-dialog">
<div class="modal-content">
<div id="content"></div> //display data output via ajax
</div>
</div>
</div>
Briefly speaking, my site has a Bootstrap modal, which is used for display a Youtube video, like following
<!-- Video dialog-->
<div class="modal fade" id="vid-modal">
<div class="modal-dialog">
<div class="modal-content">
<div class="modal-header">
<button type="button" class="close" data-dismiss="modal" aria-hidden="true">×</button>
<div class="modal-title">
<h4 id="modal-title">Modal title</h4>
</div>
</div>
<div class="modal-body">
<div class="modal-video">
<iframe src=""></iframe> <!-- Code for video here -->`
</div>
</div>
</div><!-- /.modal-content -->
</div><!-- /.modal-dialog -->
</div><!-- /.modal -->
<!-- End video dialog-->
This modal is displayed each time user clicks on a link. Those links are loaded from database using PHP with this code:
<div class="panel-group" id="accordion">
<?php
$v_units = $courses->get_distinct_unit($id);
foreach ($v_units as $v_unit) { ?>
<div class="panel-info">
<div class="panel-heading">
<h4 class="panel-title">
<a data-toggle="collapse" href="#collpase<?php echo $v_unit['unit_id'];?>"><?php echo $v_unit['unit_id'] . ' - ' . $v_unit['unit_name']; ?></a>
</h4>
</div> <!-- End of .panel-heading-->
<div id="collpase<?php echo $v_unit['unit_id'];?>" class="panel-collapse collapse in">
<div class="panel-body">
<?php $v_vids = $courses->get_unit_video($v_unit['unit_id']); ?>
<?php foreach ($v_vids as $v_vid): ?>
<a class="show-vid-modal" href="<?php echo $v_vid['vid_link']; ?>"><?php echo $v_vid['vid_title'] ?></a>
<?php endforeach ?>
</div> <!-- End of .panel-body -->
</div> <!-- End of .panel-collapse -->
</div> <!-- End of .panel-default-->
<?php }?>
</div> <!-- End of #accordion-->
The a class="show-vid-modal" ... triggers the modal.Modal's title and video link is fetched through PHP for each item.
I have added the following javascript code.
<script>
$('.show-vid-modal').click(function(e) {
e.preventDefault();
$("#vid-modal").on('show.bs.modal', function(e) {
$("h4 #modal-title").text("<?php echo $v_vid['vid_title'];"?>);
$("div .modal-video").innerHTML = "<iframe src="<?php echo $v_vid['vid_link'];?>" "
});
$("#vid-modal").modal();
});
</script>
However, it only shows the title and video of the last item for every item (as the foreach loop ends). If I put the javascript inside foreach loop, then it will not work.
Can anyone give me an idea on how I should do that.
In your modal, put an id for the iframe, so it'll be:
<iframe id="video-frame" src=""></iframe>
In your link, create a custom attribute, let's say video-src, so it'll be:
<a class="show-vid-modal" href="#" video-src="<?php echo $v_vid['vid_link']; ?>"><?php echo $v_vid['vid_title'] ?></a>
Once you have it, put in your button's click function:
$('.show-vid-modal').click(function(e) {
//here the attribute video-src is helpfull
var vid-src = $(this).attr('video-src');
var title = $(this).html();
e.preventDefault();
$("#vid-modal").on('show.bs.modal', function(e) {
$("h4 #modal-title").text(title);
//here the id for the iframe is helpfull
$('#video-frame').attr('src', vid-src);
});
$("#vid-modal").modal();
});
It might work.