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
Related
i'm coding a php site to serve on file sharing . i had a problem with hiding the delete file option from users and showing it for site admin , the actual logged in user name is stored in a php session so hiding or showing the delete option will be used in php condition .
the problem is the php code never worked to add the "hidden" option on delete img tag .
in 1st step, js, jquery and php code were separated in two files, so i had to copy jquery code in index.php (main page) since i had no other option to grab the logged in user from php session to js file.
function render(data) {
var scannedFolders = [],
scannedFiles = [];
if (scannedFiles.length) {
scannedFiles.forEach(function(f) {
var fileSize = bytesToSize(f.size),
name = escapeHTML(f.name),
fileType = name.split('.'),
icon = '<span class="icon file"></span>';
fileType = fileType[fileType.length - 1];
icon = '<span class="icon file f-' + fileType + '">.' + fileType + '</span>';
var x = f.path.replace(/\/\/+/g, '/');
var file = $('<li class="files">'+icon+'<span class="name">'+ name +'</span> <span class="details">'+fileSize+'</span></li><img src="assets/supp.png" height="42" width="42" id="logo" onclick=del("'+encodeURIComponent(x)+'") if($_SESSION['username']!='info') {?> hidden <?php } ?>>');
file.appendTo(fileList);
});
}
<?php if($_SESSION['username']!='info') echo 'hidden' ?>
You need to put your php code inside php tags. You had syntax errors in your example code.
That way if your if statement is true it will show the "hidden" parameter causing your html element to be invisible.
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.
Closed. This question needs to be more focused. It is not currently accepting answers.
Want to improve this question? Update the question so it focuses on one problem only by editing this post.
Closed 8 years ago.
Improve this question
UPDATED CODE I am trying to call a PHP scripts in my main PHP file where everything will be displayed. I just want to display the results from my PHP script with the SQL queries that are being run.
Id also like to include the possibility of showing the results dynamically/by not refreshing the page.
this is what I tried so far, im new to Jquery and AJAX. thanks in advance!
JQuery/AJAX part:
<div id="map_size" align="center">
<script type="text/javascript">
//Display station information in a hidden DIV that is toggled
//And call the php script that queries and returns the results LIVE
$(document).ready(function() {
$(".desk_box").click(function() {
$id = $(this).attr("data")
$("#station_info_"+$id).toggle();
$.ajax({
url:"display_stationinfo.php",
success:function(result){
$("#map_size").html(result);
}});//end ajax
});//end click
});//end ready
</script>
</div> <!-- end map_size -->
display_station.php (script that I want to call):
<?php
include 'db_conn.php';
//query to show workstation/desks information from DB for the DESKS
$station_sql = "SELECT coordinate_id, x_coord, y_coord, section_name FROM coordinates";
$station_result = mysqli_query($conn,$station_sql);
//see if query is good
if($station_result === false) {
die(mysqli_error());
}
//Display workstations information in a hidden DIV that is toggled
while($row = mysqli_fetch_assoc($station_result)){
//naming values
$id = $row['coordinate_id'];
$x_pos = $row['x_coord'];
$y_pos = $row['y_coord'];
$sec_name = $row['section_name'];
//display DIV with the content inside
$html = "<div class='station_info' id='station_info".$id."' style='position:absolute;left:".$x_pos."px;top:".$y_pos."px;'>Hello the id is:".$id."</br>Section:".$sec_name."</br></div>";
}//end while loop for station_result
echo $_GET['callback'] . '(' .json_encode($html) . ')';
mysqli_close($conn); // <-- DO I NEED TO INCLUDE IT HERE OR IN MY db_conn.php SINCE IM INCLUDING IT AT THE TOP?
?>
You should find out what are the ways in which you can make jquery ajax calls
Other basic tutorial which will help you in ajax is below
http://api.jquery.com/jquery.ajax/
http://www.w3schools.com/jquery/ajax_ajax.asp
http://www.w3schools.com/jquery/jquery_ajax_intro.asp
http://www.w3schools.com/jquery/jquery_ref_ajax.asp
http://www.w3schools.com/jquery/jquery_ajax_get_post.asp
http://www.tutorialspoint.com/jquery/jquery-ajax.htm
Since you have not explained clearly the question i am making genral assumption and going to give you two answer on how you can use ajax for your purpose
1.AJAX LOAD
Lets say your HTML structure is
HTML
<div id="map_size" align="center"></div>
MY JS FILE
$(document).ready(function(){
jQuery("#map_size").load("myphp.php", {}, function() { });
})
PHP
echo "<p>THIS IS TEST FOR DEMO AJAX LOAD</p>"
you can do much more if you are retrieving from db.
myphp.php
//get number of rows for X,Y coords in the table
while($row = mysqli_fetch_assoc($coord_result)){
//naming X,Y values
$x_pos = $row['x_coord'];
$y_pos = $row['y_coord'];
//draw a box with a DIV at its X,Y coord
echo "<div id='desk_box' style='style:absolute;
left: " . $x_pos. " px;
top: " . $y_pos. " px;'>box number</div>";
}
you can also do same thing on button click and load everything dynamically without refreshing page
2.Jquery Ajax [GET, POST] : Link
This also can be used
HTML
<div id="map_size" align="center"></div>
MY JS FILE
//http://api.jquery.com/jquery.ajax/
$(document).ready(function(){
$.ajax({url:"myphp.php",success:function(result){
$("#map_size").html(result);
}});
})
myphp.php
//get number of rows for X,Y coords in the table
while($row = mysqli_fetch_assoc($coord_result)){
//naming X,Y values
$x_pos = $row['x_coord'];
$y_pos = $row['y_coord'];
//draw a box with a DIV at its X,Y coord
$html = "<div id='desk_box' style='style:absolute;
left: " . $x_pos. " px;
top: " . $y_pos. " px;'>box number</div>";
}
//create a JSON
echo $_GET['callback'] . '(' . json_encode($html ) . ')';
I have a multiple drop down that goes from Country/State/city/destination.
What I want this plugin to do next, is once the destination menu is selected, the page will automatically display some general information about that destination on the same page without reloading.
The general info is in the same table as my destination drop down menu is, but under different columns.
So how can I get this information to display its self possibly in a text box or something similar only when the final distention menu is selected.
Here are some parts of my code thus far, I don't believe posting everything is necessary and might be a little confusing. PS-I am a beginner.
This is an example of my javascript which calls from my ajax.php file for the array to populate the drop down menu...
jQuery(".wrap").on('change', '#city', function() {
var querystr2 = 'cityid=' +jQuery('#city :selected').val();
jQuery.post("<?php echo plugins_url(); ?>/Destination_Drop_Down_Menu/ajax.php", querystr2, function(data) {
if(data.errorcode ==0){
jQuery('#descbo').html(data.chtml)
}else{
jQuery('#descbo').html(data.chtml)
}
}, "json");
});
This is part of my ajax.php file that previous example of jQuery is pulling information from.
$city_id = isset($_POST['cityid']) ? $_POST['cityid'] : 0;
if ($city_id <> 0) {
$errorcodeD = 0;
$strmsg = "";
$sqlD="SELECT * from destination WHERE IDCity = ". $city_id . " ORDER BY name;";
$resultD=mysql_query($sqlD);
$contD=mysql_num_rows($resultD);
if(mysql_num_rows($resultD)){
$chtmlD = '<select name="destination" id="destination"><option value="0">--Select Destination--</option>';
while($row = mysql_fetch_array($resultD)){
$chtmlD .= '<option value="'.$row['IDDestination'].'">'.$row['name'].'</option>';
}
$chtmlD .= '</select>';
echo json_encode(array("errorcode"=>$errorcodeD,"chtml"=>$chtmlD));
}else{
$errorcodeD = 1;
$strmsg = '<font style="color:#F00;">No Destination available</font>';
echo json_encode(array("errorcode"=>$errorcodeD,"chtml"=>$strmsg));
}
And MY html section that would display everything.
<h2>Destination</h2>
<div class="wrap" id="descbo">
</div>
So basically what ever destination the user chooses, the specific information for that destination will render its self on the screen in separate boxes or text areas.
Thank you!
So, if I understand correctly, you want your php script to return data from your destination table when a particular destination is selected. You said you don't want the page to reload, but I'll assume you're OK with issuing another AJAX request to the server. If that's the case, you can simply create another delegated jQuery handler for the destination <select>:
jQuery(".wrap").on('change', '#destination', function() {
var data = {destinationid: this.value};
jQuery.post("url/to/script.php", data)
.done(function(response) {
jQuery('#descbo').html(response.html);
});
Then, in your PHP, you could have something like this:
$destination_id = isset($_POST['destinationid']) ? $_POST['destinationid'] : 0;
...
$sqlD="SELECT * from destination WHERE ID = ". $destination_id . " ORDER BY name;";
$resultD=mysql_query($sqlD);
if(mysql_num_rows($resultD)){
$chtmlD = '<div class="destination">';
while($row = mysql_fetch_array($resultD)){
$chtmlD .= '<p>' . $row['whatever'] . '</p>';
}
$chtmlD .= '</div>';
echo json_encode(array("errorcode"=>$errorcodeD,"chtml"=>$chtmlD));
} else {
...
}
That will replace your original destination <select> with a div containing the destination description (or whatever the content is). If you don't want to replace the select, you could simply have the JS update a different element on the page, e.g.
jQuery('#some_other_element').html(response.html);
I'm not sure if this question is possible but what I want is to take a set of photos from Flickr and dump every url into a file (text is fine). Dumping them within anchor tags would be plus. So far I've seen this and I looked through the Galleria viewers JavaScript code but no luck. I'm expecting a simple few lines of code to do this because Galleria does it but I'm not really sure where in their code Flickr is accessed to get the image urls.
I think this might be the answer actually but if someone else comes along and has another answer I'll of course accept theirs instead of just mine.
It seems that phpflickr has this example which should work:
<?php
require_once("phpFlickr/phpFlickr.php");
// Create new phpFlickr object
$f = new phpFlickr("[API Key]");
$f->enableCache(
"db",
"mysql://[username]:[password]#[server]/[database]"
);
$i = 0;
if (!empty($_POST['username'])) {
// Find the NSID of the username inputted via the form
$person = $f->people_findByUsername($_POST['username']);
// Get the friendly URL of the user's photos
$photos_url = $f->urls_getUserPhotos($person['id']);
// Get the user's first 36 public photos
$photos = $f->people_getPublicPhotos($person['id'], NULL, NULL, 36);
// Loop through the photos and output the html
foreach ((array)$photos['photos']['photo'] as $photo) {
echo "<a href=$photos_url$photo[id]>";
echo "<img border='0' alt='$photo[title]' ".
"src=" . $f->buildPhotoURL($photo, "Square") . ">";
echo "</a>";
$i++;
// If it reaches the sixth photo, insert a line break
if ($i % 6 == 0) {
echo "<br>\n";
}
}
}
?>
<h3>Enter a username to search for</h3>
<form method='post'>
<input name='username'><br>
<input type='submit' value='Display Photos'>
</form>
<p>View Source</p>