PHP: Get next image using Jquery - php

I have a comics website which loops through all images in a db and displays them as thumbnails.
The user can click on one of those images to see it in normal size on a viewComic.php template.
I'd like to allow users to press left and right arrows to navigate images.
So, my idea is:
pagination.php handles image display on correct pages (by offsetting) by looping through database result array. The user can click on a result (below) to go to that specific image on the viewcomic.php template.
'<br />IMG: <a href="./templates/viewcomic.php?id=' . $row['imgid'] . '&image=' . $imgpath.$row['imgname'] . '">
Now on viewcomic.php, I get the id and image, and display the image
$imgid = $_GET['id'];
$imgpath = $_GET['image'];
<center><img src=".<?php echo $imgpath ?>" /></center>
The user can press left and right arrows to navigate through images...
My goal was to somehow increment the image id to move to the next image, but that doesn't seem to be working...
<script type="text/javascript">
$(document).ready(function() {
$(document).keydown(function (e) {
if (e.which == 39) { //get next image
<?php
$count = 0;
$count++;
echo "<img src=" . $imageArray[$count] . "/>";
?>
}
});
});
</script>
Any ideas?
EDIT: I'm going to go through an image array passed in from pagination.php.
So, in my viewcomic.php file, I've updated my jquery script (see above).. but the jquery doesn't seem to like the embedded php, even though it's all in a php file.
Here's a picture of page source vs code:

Here is what i would do:
assuming that an imagepath is surrounded by quotes:
echo $imageArray[0]; // 'imagepath/image'
Script:
<script type="text/javascript">
var imgArray = [<?php echo implode(',',$imageArray) ?>];
// now the image array have the list of all your images.
$(document).ready(function() {
var img = document.getElementById("theImage");
imgIndex = 0;
$(document).keydown(function (e) {
if (e.which == 39) { //get next image
img.src = imgArray[imgIndex++]
}
... /* Logic to check if at the end of imageArray */ ...
});
});
</script>
The Html:
<center><img src="" id="theImage"/></center>

How about:
$(document).ready(function() {
$(document).keydown(function (e) {
if (e.which == 39) {
var nextId = $_GET['id'] + 1;
window.location = "./templates/viewcomic.php?id=" + nextId;
}
});
});

In this case your page is submit on every request, You can also handle this at client site.
Click link to see demo about rotate link using JavaScript. : Link Rotate using javascript

Related

How to call an image alt by an onclick event using php?

I want to open a new page and transfer data from an array. Using the name of the image seemed like the easiest way so that's what i want to do.
on the page i want to call it
function meghiv($img)
{
$be=$img.alt;
echo $be;
session_start();
$_SESSION['kod'] = $be;
}
for($j=0;$j<4;$j++)
{
echo ' <img src="'.$nevek[$i].'.png" class="card-img-top " alt="'.$i.'" onclick="meghiv(this)"> ';
$i++;
}
on the new page
<?php
session_start();
echo $_SESSION['kod'];
?>
I don't know if it answers your question but try using javascript to load the image name into your php file
let images = document.querySelectorAll('.card-img-top'); // returns NodeList
let img_list = [...images]; // converts NodeList to Array
img_list.forEach(div => {
div.addEventListener("click", function(e){
e.preventDefault()
let alt = div.getAttribute("alt")
window.open(`https://link.here/?alt=${alt}`, "_blank");
})
});
Then in your php file
$image_name = $_GET['alt'];

Images refreshed without reload the page

I have a page that loads 200 or more images on one page.
All images load fine but after a few seconds, I am sending a request using
setInterval(function() {
var d = new Date();
$("#img<?php echo $row['id']; ?>").attr("src", "<?php echo SS_TLRM_IMG_EDITOR.str_replace("../","",$row['src_path']).$row['image_name']; ?>?"+d.getTime()); },
8000);
and I load new images to this same page. I call this function in a while loop.
What I am looking for:
Is there a way to refresh just the images that have been changed?
What is meant by change?
Actually, I have two pages one is used for editing images and the other is a viewer I am using wPaint js for editing images. Below you'll find screenshots of both pages.
VIEW PAGE
Editor Page
Editor page code
//while loop start here
<div class="wPaint" id="edit_<?php echo $row['id']; ?>" style="position:relative; width:<?php echo $width.'px'; ?>; height:<?php echo $height.'px'; ?>; margin:60px auto 20px auto;">
<input type="hidden" class="editEnable" value="0">
Save Image
</div>
<script type="text/javascript">
function saveImg(image) {
var _this = this;
$.ajax({
type: 'POST',
<?php if($_REQUEST['nz']==1){ ?>
url: 'ajax/upload-nz.php?imgName=<?php echo $row['
image_name ']; ?>&imgID=<?php echo $row['
id ']; ?>',
<?php }else{?>
url: 'ajax/upload.php?imgName=<?php echo $row['image_name ']; ?>&imgID=<?php echo $row['id ']; ?>',
<?php } ?>
data: {
image: image
},
success: function(resp) {
if (resp == 1 || parseInt(resp) == 1) {
_this._displayStatus('Image saved successfully');
$(this).find(".editEnable").attr('value', '2');
setTimeout(function() {
$("#saveImg<?php echo $row['id']; ?>").css({
'pointer-events': '',
'opacity': '1'
});
}, 800);
} else {
alert('Some one delete this image. You can not edit or save this image now.');
}
}
});
}
// both funciton use to load image on page load
function loadImgBg() {
this._showFileModal('bg', images);
}
function loadImgFg() {
this._showFileModal('fg', images);
}
// init wPaint
$('.wPaint').wPaint({
path: '', // set absolute path for images and cursors
autoScaleImage: true, // auto scale images to size of canvas (fg and bg)
autoCenterImage: true, // auto center images (fg and bg, default is left/top corner)
menuHandle: false, // setting to false will means menus cannot be dragged around
menuOffsetLeft: 0,
menuOffsetTop: -90,
saveImg: saveImg,
loadImgBg: loadImgBg,
loadImgFg: loadImgFg,
bg: '<?php echo SS_TLRM_IMG_EDITOR.str_replace("../","",$row['
src_path ']).$row['
image_name ']; ?>?cache=<?php echo str_replace(" ","",microtime()); ?>', // set bg on init
imageStretch: false, // stretch smaller images to full canvans dimensions
mode: 'text',
fontSize: '40',
fillStyle: '#FF0000',
fontBold: true,
strokeStyle: '#F00',
});
</script>
//while loop ended here
View Page Code
//while loop start here
<div id="edit_<?php echo $row['id']; ?>" style="position:relative; width:<?php echo $width.'px'; ?>; height:<?php echo $height.'px'; ?>; margin:0px auto 20px auto;">
<span id='ex<?php echo $row[' id ']; ?>' class="zoom"><img src='<?php echo SS_TLRM_IMG_EDITOR.str_replace("../","",$row['src_path']).$row['image_name']; ?>?cache=<?php echo str_replace(" ","",microtime()); ?>' id="img<?php echo $row['id']; ?>" />
</span>
</div>
<script>
setInterval(function() {
// Date use to prevent browser cache
var d = new Date();
$("#img<?php echo $row['id']; ?>").attr("src", "<?php echo SS_TLRM_IMG_EDITOR.str_replace(".. / ","
",$row['src_path']).$row['image_name']; ?>?" + d.getTime());
}, 15000);
</script>
//while loop ended here
Your php code loads once when the page is loaded. Your setInterval doesn't re-initialize your php code.
You can do one of three things.
1.Create an ajax call that requests the images table and updates when necessary and put the ajax call in the setInterval
2.When submitting a change have a proper php response with the image id stored in a new variable, let's say newId and the new imgSrc in a variable newImgSrc. Then with:
$("#img"+newId).attr("src", newImgSrc+"?"+d.getTime());
you can update directly the affected image.
When you load the page you can store all images using jquery. To do that you would need either a common selector or a parent for the images. SO you could enclose all images in a div with id="images-parent". In this case you can put everything in a setInterval and update like this:
setInterval(function() {
var d = new Date();
$("#images-parent").children("img").each(function() {
var newImgSrc = $(this).attr("src");
$(this).attr("src",newImgSrc+"?"+d.getTime());
});
},8000);

<button> Same Button, Multiple Locations, Different Code

I am writing an application in JQTouch, and am using a big red button
Red
I am using PHP to dynamically build the JQT page with multiple divs. The app is a server management console that gets data from MySQL. My idea is that I use a While loop to make a div for each server returned in the MySQL query, and each div will have a delete server button(the big red button). I have to call the dame bit of code because of the whole dynamic page generating thing. So I was wondering if there was a way I could have the onClick function that I call with the button
Red
know what div the button is in that is calling the function. There will be a button in multiple divs that call the same code, but i have to know WHAT server to delete. Any suggestions?
Here is the full source code.
<html>
<link rel="stylesheet" href="jq_touch/themes/css/jqtouch.css" title="jQTouch">
<script src="jq_touch/src/lib/zepto.min.js" type="text/javascript" charset="utf-8"></script>
<script src="jq_touch/src/jqtouch.min.js" type="text/javascript" charset="utf-8"></script>
<!-- Uncomment the following two lines (and comment out the previous two) to use jQuery instead of Zepto. -->
<!-- <script src="../../src/lib/jquery-1.7.min.js" type="application/x-javascript" charset="utf-8"></script> -->
<!-- <script src="../../src/jqtouch-jquery.min.js" type="application/x-javascript" charset="utf-8"></script> -->
<script src="../../extensions/jqt.themeswitcher.min.js" type="application/x-javascript" charset="utf-8"></script>
<script type="text/javascript" charset="utf-8">
var jQT = new $.jQTouch({
icon: 'jqtouch.png',
icon4: 'jqtouch4.png',
addGlossToIcon: false,
startupScreen: 'jqt_startup.png',
statusBar: 'black-translucent',
themeSelectionSelector: '#jqt #themes ul',
preloadImages: []
});
// Some sample Javascript functions:
$(function(){
// Show a swipe event on swipe test
$('#swipeme').swipe(function(evt, data) {
var details = !data ? '': '<strong>' + data.direction + '/' + data.deltaX +':' + data.deltaY + '</strong>!';
$(this).html('You swiped ' + details );
$(this).parent().after('<li>swiped!</li>')
});
$('#tapme').tap(function(){
$(this).parent().after('<li>tapped!</li>')
});
$('a[target="_blank"]').bind('click', function() {
if (confirm('This link opens in a new window.')) {
return true;
} else {
return false;
}
});
// Page animation callback events
$('#pageevents').
bind('pageAnimationStart', function(e, info){
$(this).find('.info').append('Started animating ' + info.direction + '… And the link ' +
'had this custom data: ' + $(this).data('referrer').data('custom') + '<br>');
}).
bind('pageAnimationEnd', function(e, info){
$(this).find('.info').append('Finished animating ' + info.direction + '.<br><br>');
});
// Page animations end with AJAX callback event, example 1 (load remote HTML only first time)
$('#callback').bind('pageAnimationEnd', function(e, info){
// Make sure the data hasn't already been loaded (we'll set 'loaded' to true a couple lines further down)
if (!$(this).data('loaded')) {
// Append a placeholder in case the remote HTML takes its sweet time making it back
// Then, overwrite the "Loading" placeholder text with the remote HTML
$(this).append($('<div>Loading</div>').load('ajax.html .info', function() {
// Set the 'loaded' var to true so we know not to reload
// the HTML next time the #callback div animation ends
$(this).parent().data('loaded', true);
}));
}
});
// Orientation callback event
$('#jqt').bind('turn', function(e, data){
$('#orient').html('Orientation: ' + data.orientation);
});
});
</script><?php
//Connect
mysql_connect("localhost", "root", "root") or die(mysql_error());
//Make and store queries
mysql_select_db("servermgr") or die(mysql_error());
$result = mysql_query("SELECT * FROM servers")
or die(mysql_error());
//Echo some constant HTML
echo'<div id="serverset">';
echo'<div class="toolbar">';
echo'<h1>Servers Home</h1> ';
echo'</div>';
echo'<ul class="rounded">';
//Begin printing out MYSQL rows (List Items)
while($row = mysql_fetch_array( $result )) {
//$row_friendlyName = $_row['friendly_name']
$friendlyName_noSpaces = str_replace(' ', '_', $row[friendly_name]);
echo'<li class="">'.$row["friendly_name"].'</li>';
}
//Close list
echo'</ul>';
echo '</div>';
//Redo all previous queries to print out the divs
mysql_select_db("servermgr") or die(mysql_error());
$result2 = mysql_query("SELECT * FROM servers")
or die(mysql_error());
while($row2 = mysql_fetch_array( $result2 )) {
$friendlyName_noSpaces2 = str_replace(' ', '_', $row2[friendly_name]);
echo '<div id="'.$friendlyName_noSpaces2.'">';
echo'<div class="toolbar">';
echo'<h1>'.$row2[friendly_name].'</h1> ';
echo 'Back';
echo'</div>';
echo'<ul class="rounded">';
echo '<li>Friendly Name: '.$row2[friendly_name].'</li>';
echo '<li>IP Address: '.$row2[ip].'</li>';
echo '<li>Server Hostname: '.$row2[hostname].'</li>';
echo '<li>MAC Address: '.$row2[MAC].'</li>';
echo'</ul>';
echo'<button href="#" class="redButton">Red</button>';
echo'</div>';
}
//END OF PHP
?>
</body>
</html>
add a data attribute to your "Big Red Button" as follows
Red
and from your handling code retrieve the data value as follows
var server = $(this).attr('data-server');
Then you can do your condition logic.
DevZer0's answer is probably what you want to go with but an alternative approach is to add a class to the containing div like
echo '<div id="'.$friendlyName_noSpaces2.'" class="server">';
Then you can do this in your callback
var server = $(this).closest(".server").attr("id");
to get the id of the containing div.

Jquery file picker from server

I'm making a form in php. I want the visitor to either upload an image (that part is done) or select one from the uploaded files. Is there any cool jQuery/php script that will solve this?
I'm thinking a small dialog that shows all the images from a selected folder. When the visitor clicks on foo.jpg (with thumbnail) the value in the text field would be "foo.jpg"
Any ideas?
Thanks!
Just scan the images directory like that:
<?php $dir = '/path/to/dir';
$files1 = scandir($dir);
foreach ($files1 as $value) {
echo '<p class="images">'.$value.'</p>';
echo '<img class="clickableimg" id="'.$value.'" src="path/to/'.$value.'" />';
} ?>
And you can add event on class 'images':
<script>
$(".images").click(function() {
var choosenpic = $(this).html();
$("#yourinputfieldID").val(choosenpic);
});
$(".clickableimg").click(function() {
var choosenpic = $(this).attr('id');
$("#yourinputfieldID").val(choosenpic);
});
</script>

slideshow with next and previous links not working (images came from db)

i'm creating a simple slideshow. 4 images coming from db by php stored in a div called home_gallery_thumb with relative position and the images are wrapped inside anchor tag trying to change them with a next and previous buttons but it jumps to the third image then everything stops completely though it works without any problem if these images are static not coming from the db here's the div fetching images
<div class="home_gallery_thumb" style="background-color:#006; position:relative;">
<?php
require('_req/base.php');
$getImgsQ = "select Photo_Name from photos order by Photo_ID DESC limit 4";
$getImgsR = mysql_query($getImgsQ);
while($galleryRow = mysql_fetch_array($getImgsR)){
?> <a class="galleryLink" style="position:absolute;" href="products_large/<?php echo $galleryRow['Photo_Name']; ?>"><img src="products_thumb/<?php echo $galleryRow['Photo_Name']; ?>" /></a> <?php
}
mysql_close($connect);
?>
so now i have links with images inside the div and here's the jq code
$(".home_gallery_thumb a.galleryLink").css("display","none");
$("a.galleryLink:first").fadeIn(500);
var allImgs = $(".home_gallery_thumb a").length;
$(".next").click(function(){
var curImg = $("a.galleryLink:visible").index();
var nxtImg = curImg+1 ;
if(nxtImg == allImgs) { nxtImg = 0; }
$("a.galleryLink:eq("+curImg+")").fadeOut(800,function(){
$("a.galleryLink:eq("+nxtImg+")").fadeIn(800);
});
});
$(".previous").click(function(){
var curImg = $("a.galleryLink:visible").index();
var prevImg = curImg-1 ;
if(prevImg == -1) { prevImg = allImgs-1; }
$("a.galleryLink:eq("+curImg+")").fadeOut(800,function(){
$("a.galleryLink:eq("+prevImg+")").fadeIn(800);
});
});
this code is inside document.ready and that's what i noticed through firebug
first : images load and all other links are : display:none
after clicking next button first link doesn't get display:none style and it jumps to the third link making it visible then everything stops. And the previous button does nothing at all as it doesn't exist
try this, if not work, provide a link to your slide
$("a.galleryLink").hide();
$("a.galleryLink:first-child").fadeIn(500);
$(".next").click(function(){
var curImg = $("a.galleryLink:visible");
var nxtImg = curImg.next();
if(!nxtImg.length) { nxtImg = $("a.galleryLink:first-child"); }
curImg.fadeOut(800,function(){
nxtImg.fadeIn();
});
});
$(".previous").click(function(){
var curImg = $("a.galleryLink:visible");
var prvImg = curImg.prev();
if(!prvImg.length) { prvImg = $("a.galleryLink:last-child"); }
curImg.fadeOut(800,function(){
prvImg.fadeIn();
});
});

Categories