Using PHP and JavaScript to display rotating images - javascript

What i'm trying to do is do display images from a directory and rotate every x seconds, in
this case 2 seconds.
I wrote this java script code and it works great but the image names are hard coded.
<script language="javascript" type="text/javascript">
img2 = new Image()
seconds = "2";
function imgOne()
{
setTimeout("imgTwo()", seconds * 1000);
}
function imgTwo()
{
document.myimg.src = "pics/WM/IMAGE02";
setTimeout("imgThree()", seconds * 1000);
}
function imgThree()
{
document.myimg.src = "pics/WM/IMAGE01";
setTimeout("imgOne()", seconds * 1000);
}
So I'm trying to use PHP to read the directory and create the javascript but am getting an internal server error. I'm using $p so it's img1 instead of imgOne so I can increase it. It loops thru and after the end loops back to 1. Any help is appreciated.
<?php
$files = glob('pics/WM/*.jpg');
echo
'
<script language="javascript" type="text/javascript">
img2 = new Image()
seconds = "2";
function img1()
{
setTimeout("img2()"), seconds * 1000);
}
'
$p=2;
for ($i=0; $i < count($files) $i++)
{
$image=$files[$i];
echo 'function img' .$p . '()'
echo '{'
echo 'document.myimg.src = "' .$image . '";'
$p++;
echo 'set Timeout(img"' .$p . '()", seconds * 1000); '
echo '}'
}
echo 'function img' .$p . '()'
echo '
{
document.img src="IMAGE01";
set Timeout("img1()", seconds * 1000);
}
</script> '
?>

the echostatements in your php scripts are missing the final ;. This should be the problem that causes the internal server error.
How to fix your implementation:
You should write something like
// using multiple echo statements
echo "..... your string ... ";
echo $p;
echo "--- something else ----";
// or you can concatenate strings with .
echo ".... your string ... " . $p . "---- something else ----";
Similar but safer and clearer PHP implementation:
Printing out Javascript code via PHP could be error prone, therefore I would recommend to use output big parts of text outside PHP code, like this
Some text where p = <?php echo $p; ?> is printed out.
How to improve the Javascript part:
Load all images at once
This is not related on the specific question, but simplifies your solution. Regarding your own project (rotating images), as suggested in the comments there are many reusable javascript components you can use (firstly using some javascript libraries, e.g. jQuery). But if you want to develop this feature by yourself, keep in mind that changing the src attribute of an image tells the browser to download it from scratch, resulting in glitches. To solve this issue, you may insert many <img> elements and than display it one at the time (using css styling directives).
Iterate over the images using one timed function
Furthermore, you could simplify your javascript code: instead of using a different function to display each image you can use global variables (i.e. window.my_rotate_current_img_id) or better clojures to select and show the current image:
// 1. Declare an array of img tags ID, identifying the different images
// Note that we are using PHP to generate the array - the implode function
// concatenates array items into a string separated by the first argument
// given
var images = [<?php echo '"' . implode('","', $images) . '"'; ?>];
// 2. Define a function that shows the correct image
function hide_first_and_show_second(first, second){ ... }
// img_num is the number of images to rotate
var update_img = function(idx){
return function(){
hide_idx = idx;
show_idx = (idx + 1) % img_num;
hide_first_and_show_second(hide_idx, show_idx);
}
};
setInterval(update_img(0), 1000);
This are possible (and useful) improvements of your solution for this problem. Hope i clarified.

Related

I want to load the background first using jquery but my code doesn't seem to work

Below is the code. but i don't know what the problem is. I have a array of background images after each load it keeps changing[This is my intention]. Now i planned to use javascript to load the background first but my code doesn't work though it works with regular style tags. I don't know what am doing wrong here. below are the code.
This below code works but takes time to load the image
<?php
$bg = array('login_bg.jpg', 'login_bg2.jpg', 'login_bg3.jpg', 'login_bg4.jpg', 'login_bg5.jpg', 'login_bg6.jpg', 'login_bg7.jpg', 'login_bg8.jpg', 'login_bg9.jpg' ); // array of filenames
$i = rand(0, count($bg)-1); // generate random number size of the array
$selectedBg = $bg[$i]; // set variable equal to which random filename was chosen
?>
<style>
body{
background-image:url("<?php echo $base_url; ?>assets/images/<?php echo $selectedBg; ?>");
}
</style>
This code doesn't work. I'm doing this because i want to load the BG first.
<?php
$bg = array('login_bg.jpg', 'login_bg2.jpg', 'login_bg3.jpg', 'login_bg4.jpg', 'login_bg5.jpg', 'login_bg6.jpg', 'login_bg7.jpg', 'login_bg8.jpg', 'login_bg9.jpg' ); // array of filenames
$i = rand(0, count($bg)-1); // generate random number size of the array
$selectedBg = "$bg[$i]"; // set variable equal to which random filename was chosen
?>
<script>
var img1 = new Image();
img1.src="<?php echo $base_url; ?>assets/images/<?php echo $selectedBg; ?>";
$('body').css('background-image', 'url('+ img1.src + ')');
</script>
Is your path correct?
In my example, this would be this:
http://localhost/test/assets/images/login_bg.jpg
called from this file:
http://localhost/test/index.php
Edit & Accepted answer:
Your JS/jQuery is faster than your site. Try to use $( document ).ready(function() {
$( document ).ready(function() {
$('body').css('background-image', 'url('+ img1.src + ')');
});
Why?
Because your site will be rendered from top to bottom. If you have JS/jQuery that will add something to your HTML, but the HTML is not rendered yet, it won't add something because jQuery will not find the item that you want to manipulate.
That's why you should include a JS-file at the bottom of your HTML-file.
But if you added it directly to your <head>, you have to it with $( document ).ready(function() { to be sure that your JS/jQuery will work.
Possible alternative is the standard JS onload function:
window.onload = function() {};
You should modify like this:
PHP:
It should be like $selectedBg = $bg[$i]; instead of "$bg[$i];"
<?php
$bg = array('login_bg.jpg', 'login_bg2.jpg', 'login_bg3.jpg', 'login_bg4.jpg', 'login_bg5.jpg', 'login_bg6.jpg', 'login_bg7.jpg', 'login_bg8.jpg', 'login_bg9.jpg' ); // array of filenames
$i = rand(0, count($bg)-1); // generate random number size of the array
$selectedBg = $bg[$i]; // set variable equal to which random filename was chosen
?>
HTML:
You need to add body tag also to get it working.
<body>
<script src="jquery.min.js"></script>
<script>
var img1 = new Image();
img1.src="<?php echo $base_url; ?>assets/images/<?php echo $selectedBg; ?>";
$('body').css('background-image', 'url('+ img1.src + ')');
</script>
</body>
Another thing:
Make sure $base_url; is declared.
You can simply use like below.
<script>
$('body').css('background-image', 'url(<?php echo $base_url; ?>assets/images/<?php echo $selectedBg; ?>)');
</script>

Passing encoded variable from php and decoding in javascript?

I have a very ugly piece of code in php that does something like this:
for ($i = 0; $i <= ($fi_int-1); $i++) {
$song_uri = urlencode($songs[$i]);
echo "URI: " . $song_uri . "<br>";
echo "<li><a href='#' onclick='PlaySong(".$song_uri.")'>" . $songs[$i] . "</li><br>";
}
Now when PlaySong() is being called, this happens:
<script>
function PlaySong(title) {
title = decodeURIcomponent(title));
document.getElementById("player").src = "./mp3/" + title;
}
</script>
The current problem is when $songs[$i] is being passed to PlaySong(), it looks like that right away:
PlaySong(Name+Of+The+Song+-+Artist+LastName+blah) {
...
}
So JS obviously has a problem with it. It tries to add things, because there are pluses... Now how can I convert that mess to string right when it comes in? Or is there a better way to do it? I'm sure there is but this ugliness is strictly for me, so I don't care too much about fast performance :)
You need some quotes around the song_uri string. I can't paste code on mobile... but the php should output like this
Onclick="PlaySong ('this+song')"
At the moment you've got it doing
Onclick="PlaySong(this+song)" and the argument isn't being treated as a string

pie charts are overlapping in php page

With <canvas> and JavaScript in php,I am trying to draw multiple pie charts.But charts are overlapping.
Here my javascript code:
printf('<script type="text/javascript">');
?>
function drawPie(data)
{
var ctx = $("#mycanvas").get(0).getContext("2d");
var piedata = [];
$.each(data,function(i,val){
piedata.push({value:val.count,color:val.color,label:val.status});
});
new Chart(ctx).Pie(piedata);
}
<?php
printf('</script>');
PHP code:
$data = statusPool($pool);//fetching database values(array() of label and count )
printf('<canvas id="mycanvas" width="500" height="300"></canvas>');
$data3 = json_encode($data, JSON_NUMERIC_CHECK);
echo '<script type="text/javascript"> drawPie('.$data3.'); </script>';
printf( '<table ><tr>' );
$poolArray =array(//some values)
$chartCount = 0;
foreach ( $poolArray as $pool )
{
if ($chartCount == 2)
{
printf('</tr><tr>');
$chartCount = 0;
}
printf('<td style="text-align: center;"><canvas id="mycanvas"width="256" height="256"></canvas>');
$data = statusPool($pool);
$data3 = json_encode($data2, JSON_NUMERIC_CHECK)
echo '<script type="text/javascript"> drawPie(' . $data3 . ');</script>';
$chartCount++;
printf('</a></td>')
}
printf( '</tr></table>' );
First <canvas> is for big pie chart and other small charts will come in table.
But all the charts are overlapped.
Can you tell me how to get rid of that overlapping.
Thanks in advance.
Thank you for adding the screenshot! The problem, as far as I can see, is, that all of your canvas elements have the same ID "mycanvas". In HTML, all objects are supposed to have an unique ID (if you give one to them at all). Classes can be used for more than one object, and one object can have multiple classes. It is like all employees of a company usually have different names (id) to identify them, but several people can be assigned a specific team (class) and people can also be in more than one team. If people have the same name, it usually causes confusion in the office. You have the same problem here.
To fix it, give every canvas an unique id. This could look similar to this:
echo '<td style="text-align: center;"><canvas id="pie-canvas-'
. $canvasId
. '"width="256" height="256"></canvas>';
Pass the ID you gave to your canvas to the function that is drawing it.
echo '<script type="text/javascript">drawPie('
. $canvasId
. ', '
. $data3
. ');</script>';
I don't really know what is in $data2 or $data3, but I assume it also contains something like an ID that you could use for this purpose. If not, let the loop iterate a variable and use its value as ID. When you add the script to draw the current pi in the loop, pass the ID as parameter (if you do not already do it with $data3) and select the particular canvas from the document using
function drawPie(canvasId, data) {
[...]
var ctx = $("#pie-canvas-" + canvasId).getContext("2d");
[...]
}
Btw. you have some errors in your code like missing semicolons, unopened or unclosed HTML tags, etc.

How to make a slideshow banner in html?

I want to make my banner changed automatically just like a slideshow. The banner I took from a folder and it can read all banner in that folder and display it on a website automatically changes. I already make it to read all banner and display it on the website, but it kind of random image, not changed except if I reload the page. This the code:
<?php
$imglist='';
//$img_folder is the variable that holds the path to the banner images.
// see that you dont forget about the "/" at the end
$img_folder = "images/";
mt_srand( (double)microtime()*1000 );
//use the directory class
$imgs = dir($img_folder);
//read all files from the directory, checks if are images and ads them to a list (see below how to display flash banners)
while ( $file = $imgs->read() )
{
if (eregi("gif", $file) || eregi("jpg", $file) || eregi("png", $file))
$imglist .= "$file ";
}
closedir($imgs->handle);
//put all images into an array
$imglist = explode(" ", $imglist); $no = sizeof($imglist)-2;
//generate a random number between 0 and the number of images
$random = mt_rand(0, $no); $image = $imglist[$random];
//display image
echo '<img class="img-responsive" src="'.$img_folder.$image.'" border=0>';
?>
And how to make that PHP into HTML? if I change the extention into html, the banner div show the code not the images. Thanks.
The psuedocode for what you're doing would go something like:
load images from a directory into an array
on page load select a random image from image array
display first image
every X seconds display another image from image array
to display properly, your php file needs to be loaded/served from a web server. To do this, deploy your php file to your web server and then test it out.
an example of a banner I created a few years agao, that is similar to what you are after, is here
First, make your PHP echo out a hidden <input> element, with value containing the JSON string of image paths. Using your code, something like:
<?php
$out = " /* Beginning of your page code */ "
$imgJSON = json_encode($imglist);
$out .= '<input id="bans" type="hidden" value="' .$imgJSON. '" />';
$out .= " /* Rest of your page code */ "
echo $out;
die();
Then, you can use the example below to swap the images in the banner div. I demonstrate a very simple animation, just to show how it is done.
jsFiddle Demo
HTML:
<!-- Not req if you echoed out a hidden input via PHP:
<input type="hidden" id="bans" value='["300/49","300/51","297/50","298/51"]' />
-->
<div id="banner"></div>
javascript/jQuery:
var i = $('#bans').val();
var j = JSON.parse(i);
var max = j.length - 1;
var cnt = 0;
var timerId = null;
function swapBannersTimer() {
doSwap();
timerId = setTimeout(swapBannersTimer, 3000);
}
function doSwap(){
var str = 'http://placekitten.com/' + j[cnt];
$('#banner')
.html('<img class="far_right" src="'+str+'" />')
.promise()
.done(function(){
$('img').animate({
marginLeft: '0px'
},500);
});
cnt = (cnt < max) ? cnt+1 : 0;
}
swapBannersTimer();
**CSS:*
#banner{width:300px;height:52px;overflow:hidden;}
.far_right{margin-left:300px;}
NOTE: Because this example uses the jQuery library, you must include it on your page -- usually between the DIV tags, like this:
<head>
<!-- other stuff in head -->
<script src="//ajax.googleapis.com/ajax/libs/jquery/1.9.1/jquery.min.js"></script>
</head>
If you use a CDN to load jQuery, as in the above example, it is probably already be pre-loaded from other websites.
If you want some fast lessons on jQuery, find free video tuts here:
https://www.thenewboston.com/videos.php?cat=32
or at
https://phpacademy.org/videos/jquery-basics

javascript call inside php where loop not working and breaks query

I am attempting to call a javascript function inside a php where loop. I've succeeded in calling the variable, however the function only works on the first line, and then breaks a subsequent query.
The javascript is a simple show/hide of a div or span tag with a specific id. I'm trying to have this appear for every instance of a variable, but only open the span associated with that entry, so I used a php variable from the query.
The javascript code is contained in the header; it works fine without the php, and the php works fine without the javascript but I can't seem to make them work together.
Here's the code:
while($row = mysqli_fetch_array($qir)) {
$ingredient_id = $row['ingredient_id'];
echo '<input type="checkbox" value="' . $ingredient_id . '" name="markdelete[]">';
echo $row['amt'] . ' ' .$row['ingredient_name']; ?> <button onclick="showHide('<?php echo $row['ingredient_id']; ?>'); return false">Edit amount</button> <br />
<span id="<?php echo $row['ingredient_id']; ?>" class="hide">
<?php include_once('amt.php');
echo '</span> ';
// }
echo '<br />';
}
echo '<input type ="submit" name="remove" value="Remove">';
First of all, the showHide is only working on the first record
It is also making this query not respond at all.
if (isset($_POST['remove'])) {
iF (!empty($_POST['markdelete'])) {
foreach ($_POST['markdelete'] as $delete_id) {
// remove specific source from source_subject
$rem_ing = "DELETE from dish_ingredient
where ingredient_id = $delete_id
and dish_id = $dish_id ";
mysqli_query($dbc, $rem_ing)
or die ('Error removing ingredient: '.mysqli_error($dbc));
}
}
}
I tried removing the return false;, to no avail. Please let me know if I need to show more of the code (e.g. the javascript itself)
Edit:
I've tried working within the php string (this is actually what I had tried first) but it seems to break everything (no javascript, no php)
echo $row['amt'] . ' ' .$row['ingredient_name'] . '<button onclick="showHide(\''. $row['ingredient_id'] .'\') return false">Edit amount</button> <br />';
echo '<span id=" '. $row['ingredient_id'] .' " class="hide">';
include_once('amt.php');
echo '</span> ';
Edit: I am open to other solutions if this is not something that is possible. I'm feeling a bit stumped. Realistically I just want to have a list of items called from a mysql database, and have a field appear onclick to edit an associated variable if desired without having to send it to another page or reload the script for usability (hence the javascript piece).
Thanks again, anyone who can assist.
Note: this is the script that I am calling:
<script language="JavaScript" type="text/JavaScript">
menu_status = new Array();
function showHide(theid){
if (document.getElementById) {
var switch_id = document.getElementById(theid);
if(menu_status[theid] != 'show') {
switch_id.className = 'show';
menu_status[theid] = 'show';
}else{
switch_id.className = 'hide';
menu_status[theid] = 'hide';
}
}
}
</script>
You don't need tag there as you are already in php block.Try it without and use
showHide(\''.$row['ingredient_id'].'\')
and change
<?php include_once(....);
to
include_once(........);
Hopefully that would work
===========
try this for you javascript
<script language="JavaScript" type="text/JavaScript">
function showHide(theid){
if (document.getElementById) {
var switch_id = document.getElementById(theid);
if(!switch_id) {
switch_id.className = (switch_id.className.indexOf("show") > -1) ? "hide" : "show"
}
}
}
Okay after a long time on this, I finally figured out what was going on. Part of the issue was that I was trying to call a form inside a form, which I had forgotten is not permitted in HTML, so this required some redesign.
Other issues involved calling loops within inside loops, which caused problems where the first record would work, but not for the remaining records.
The javascript above did not need to be modified, only the way that it was called.
Here is what worked. The main key was using include() instead of include_once().
while($r = $qir->fetch_assoc()) {
$ingredient_id = $r['ingredient_id'];
$amt = $r['amt'];
$ingredient_name = $r['ingredient_name'];
echo $r['amt'] . ' ' .$r['ingredient_name'];
if ($row['user_id'] == $user_id) {
echo ' <span class="openlink"><button onclick="showHide(\''.$ingredient_id. '\')">edit amount</button></span><br/>';
echo '<div id="'.$ingredient_id.'" class="hide">';
include('amt1.php');
echo '</div>';
}
}

Categories