I have a li and inside that i have a div class="reload" that have some content that should be reloaded for every 10 sec.
<li class="b1">
<div class="reload">
</div>
</li><!--col-->
So therefore i have got a script that does just that.
<script type="text/javascript">
$('.b1').children('.reload').load('php/reload/reload.php'); // load the content at start
window.setInterval(function(e) {
$('.b1').children('.reload').load('php/reload/reload.php'); // reload the content every 10 sec
}, 10000);
In the reload.php i get some content from a database. It looks like this, sort of..
<?php
// login info
require("../../connection_to_database_login.php");
// My query
$result = mysqli_query($l,'SELECT * FROM abcd WHERE efg=1 LIMIT 1');
// include some stuff
$r = mysqli_fetch_row($result);for ($p = 0; $p < $r[4]; ++$p){include("../some/stuff_$p.php");};
// include a random picture script or just load a picture
if ($r[4] == 0){include ('getRandPic.php');}
else {echo ('<img src="images/picture.png" />');}
?>
So far so good.. everything works.
The getRandPic.php file.. select one random picture from a folder
<?php
$img_dir = "images/images";
$images = scandir($img_dir);
$html = array();
foreach($images as $img) {
if($img === '.' || $img === '..') {continue;}
if ( (preg_match('/.jpg/',$img)) || (preg_match('/.gif/',$img)) || (preg_match('/.tiff/',$img)) || (preg_match('/.png/',$img)) ) {
$html[] .= '<img class="img-responsive" src="'.$img_dir.$img.'" />';
}
else { continue; }
};
echo $html[rand(0,6)];
?>
So this works ok.
But the thing is, i want to check if it shall "include a random picture script or just load a picture" every 5sec.
Therefore i need to check "if ($r[4] == 0)" every 5 sec.
So my question is: Is there any other way to do that?
As you asked in the comment... This is a rough guide only. You will have to develop and write your own code based on this guide.
Step 1a: optional
Make an ajax call from your webpage to the server. to get image file names.
Step 1b:
On server side in php file perform DB operation.
Let assume you have a table imageTable and column name images so you would read from DB using query SELECT images FROM imageTable
You will have to change the query, add condition (e.g. all images with animal and cute tags) to it and if you want limit the number of files that you want to randomize then you will have to add that as well.
Step 2:
Once you read from DB, as you are already doing, read all image names and put it in json format (json_encode). I personally prefer json. If you prefer, you can also return all names in simple string where names are separated by comma.
Step 3:
Store your response in JS.
var imagesArray = new Array();
$.ajax({
type: 'post',
url: pathtophpfile,
success: function(htmll) {
// get object with all data
imagesArray= JSON.parse(htmll);
},
});
Step 4:
Once you have it in your js object named imagesArray, use setInetval to perform task every 5 seconds.
Read a random value from 0 to imagesArrays length, and change the source of your image tag, <img class="img-responsive" src="+ randomimage +" />
Periodic updater will do your task.
Use ajax framework, it will reduce your db connection burden at the server side.
Have a look at it. It is a simple and nice way to achieve your task.
http://prototypejs.org/doc/latest/ajax/Ajax/PeriodicalUpdater/
Related
I have created a php page to display a image from a set of five images. The image is displayed based on the data read from a text file.Another application is continuously updating data in that text file.So my php page need to read data from that file whenever the file is updated and display image based on that data. I created a infinite loop to read data. But when i tried to access the php page from a browser , it is not loading because of the infinite loop.
$myfile1 = fopen("readfile.txt", "r") or die("Unable to open file!");
$readJsonData = fread($myfile1,filesize("readfile.txt"));
fclose($myfile1);
$obj = json_decode($readJsonData);
$urllogo = 'tatalogo.png';
if(($obj->{"FrontLeft"}) == "TRUE")
{
$url = 'images/FrontLeft.png';
}
else if(($obj->{"FrontRight"}) == "TRUE")
{
$url = 'images/FrontRight.png';
}
else if(($obj->{"RearLeft"}) == "TRUE")
{
$url = 'images/RearLeft.png';
}
else if(($obj->{"RearRight"}) == "TRUE")
{
$url = 'images/RearRight.png';
}
else
{
$url = 'images/Normal.png';
}
// infinite loop
while(1)
{
//reading from the file and refreshing the page.
}
In PHP Set header like this to refresh the php page
header("Refresh: 5;url='pagename.php'");
In HTML Head tag
<html>
<head>
<meta http-equiv="refresh" content="5;URL='pagename.php'">
</head>
</html>
<?php
Your php script here..
?>
Using Javascript
<script type="text/javascript>
window.setInterval(function(){
reload_page();
}, 5000);
//Here 5000 in miliseconds so for 5 seconds use 5000
function reload_page()
{
window.location = 'pagename.php';
}
The most reasonable way to do it would be to use the client side to refresh the page.
Get rid of all that infinite loop stuff on the PHP side. PHP will only output the image as it stands at the moment it was generated.
On the client side you could do something as simple as:
<META http-equiv="refresh" content="5;"> to force a refresh every 5 seconds.
If you only want to update when the file is updated you have to get more advanced. You could do an ajax call that checks if the file has changed and if so it refreshes. Websockets would be another option.
You could possibly do some nasty hack on the PHP side to make it work using ob_flush and sleep and header within a loop that checks to see if the file has changed but this will cause you to lose sleep once you realize what you've done. As pointed out below, this would never work.
I'm trying to do something a little different with a banner rotator.
Below is the script I am using to read two text files (stored on my root directory with .db extensions) to rotate banners on a website. One file holds a counter (FileDB), the other holds the HTML banner code (URLDB).
The URLDB file currently holds six lines of HTML code to display hyperlinked banners.
The following script builds an array and rotates these banners sequentially on the refresh of the page counting from 0 - 5, and it does this perfectly:
<?php
define('FILEDB', '/WORKING DIRECTORY/count.db');
define('URLDB', '/WORKING DIRECTORY/url.db');
function readURLS()
{
$fo = fopen(URLDB, 'r');
if( null == $fo )
return false;
$retval = array();
while (($line = fgets($fo)) !== false)
{
$retval[] = $line;
}
return $retval;
}
$list = readURLS();
if( false === $list )
{
echo "No URLs available";
}
else
{
$fo = fopen(FILEDB, 'a+');
$count = (fread($fo, filesize(FILEDB)) + 1) % count($list);
ftruncate($fo, 0);
fwrite($fo, "{$count}");
fclose($fo);
echo $list[$count];
}
?>
On the webpage that I want to display the banners there are eight placeholders. However I only have six banners.
Here is the PHP code in each of the placeholders:
Placeholder 1: <?php echo $list[$count];?>
Placeholder 2: <?php echo $list[$count +1];?>
Placeholder 3: <?php echo $list[$count +2];?>
Placeholder 4: <?php echo $list[$count +3];?>
Placeholder 5: <?php echo $list[$count +4];?>
Placeholder 6: <?php echo $list[$count +5];?>
Placeholder 7: <?php echo $list[$count +6];?>
Placeholder 8: <?php echo $list[$count +7];?>
With the count at 0 the 6 banners are displayed in placeholders 1 - 6 and placeholders 7 and 8 are blank.
With every refresh the counter is increase by one, showing each banner in the first placed holder and pulling the other banners through each placeholder from 5 through to 0, but leaving previously populated placeholders blank until the sixth banner is in placeholder one. Then on the next refresh banners 1 - 6 are once again shown.
This occurs because I've hardcoded the values in each placeholder and I am obviously attempting to reference an entry in the file that is out of the bounds of the array built by the above script.
You can see a working example here.
What I am trying to achieve is display all banners in the URLDB such that when the last entry is shown, the first entry is displayed in the next placeholder (which in this case is placeholder 7) and the 2nd entry is show in in placeholder 8.
The idea is that the banners move continuously through each of the placeholders like the carriages of a train with each page refresh and increment of the counter - one following the other.
So, now you have the background, on to my question.
Is there a way I can amend the script to store in a PHP variable the maximum number of entries in the URLDB file/array and subsequently add conditional processing in the placeholders to check when the counter reaches this maximum value, and reference the next valid value in the array (i.e. 0) such that the banners restart again in the surplus placeholders - so here are no blank or empty placeholders shown?
I imagine this might seem like a strange request. But of course I would appreciate any advice on how to achieve my goal based on where things are currently.
Once you use a loop things become a bit easier to manipulate.
Hopefully the following solves your problem.
$numOfBanners = count($list);
$numOfPlacements = 8;
for ($i=0; $i < $numOfPlacements; $i++) {
// use the modulus operator to come back around
$bannerID = $i % $numOfBanners;
echo $list[$bannerID];
}
More info on the modulus operator can be found here.
Iam getting offsetwidth of an div tag. Below is code.
<body>
<div id="marqueeborder" onmouseover="pxptick=0" onmouseout="pxptick=scrollspeed">
<div id="marqueecontent">
<?php
// Original script by Walter Heitman Jr, first published on http://techblog.shanock.com
// List your stocks here, separated by commas, no spaces, in the order you want them displayed:
$stocks = "idt,iye,mill,pwer,spy,f,msft,x,sbux,sne,ge,dow,t";
// Function to copy a stock quote CSV from Yahoo to the local cache. CSV contains symbol, price, and change
function upsfile($stock) { copy("http://finance.yahoo.com/d/quotes.csv?s=$stock&f=sl1c1&e=.csv","stockcache/".$stock.".csv"); }
foreach ( explode(",", $stocks) as $stock ) {
// Where the stock quote info file should be...
$local_file = "stockcache/".$stock.".csv";
// ...if it exists. If not, download it.
if (!file_exists($local_file)) { upsfile($stock); }
// Else,If it's out-of-date by 15 mins (900 seconds) or more, update it.
elseif (filemtime($local_file) <= (time() - 900)) { upsfile($stock); }
// Open the file, load our values into an array...
$local_file = fopen ("stockcache/".$stock.".csv","r");
$stock_info = fgetcsv ($local_file, 1000, ",");
// ...format, and output them. I made the symbols into links to Yahoo's stock pages.
echo "<span class=\"stockbox\">".$stock_info[0]." ".sprintf("%.2f",$stock_info[1])." <span style=\"";
// Green prices for up, red for down
if ($stock_info[2]>=0) { echo "color: #009900;\">↑"; }
elseif ($stock_info[2]<0) { echo "color: #ff0000;\">↓"; }
echo sprintf("%.2f",abs($stock_info[2]))."</span></span>\n";
// Done!
fclose($local_file);
}
?>
<span class="stockbox" style="font-size:0.6em">Quotes from Yahoo Finance</span>
</div>
</div>
</body>
below is the javascript function which will be called onlaod of the page.
<script type="text/javascript">
// Original script by Walter Heitman Jr, first published on http://techblog.shanock.com
// Set an initial scroll speed. This equates to the number of pixels shifted per tick
var scrollspeed=2;
var pxptick=scrollspeed;
function startmarquee(){
alert("hi");
// Make a shortcut referencing our div with the content we want to scroll
var marqueediv=document.getElementById("marqueecontent");
alert("marqueediv"+marqueediv);
alert("hi"+marqueediv.innerHTML);
// Get the total width of our available scroll area
var marqueewidth=document.getElementById("marqueeborder").offsetWidth;
alert("marqueewidth"+marqueewidth);
// Get the width of the content we want to scroll
var contentwidth=marqueediv.offsetWidth;
alert("contentwidth"+contentwidth);
// Start the ticker at 50 milliseconds per tick, adjust this to suit your preferences
// Be warned, setting this lower has heavy impact on client-side CPU usage. Be gentle.
var lefttime=setInterval("scrollmarquee()",50);
alert("lefttime"+lefttime);
}
function scrollmarquee(){
// Check position of the div, then shift it left by the set amount of pixels.
if (parseInt(marqueediv.style.left)>(contentwidth*(-1)))
marqueediv.style.left=parseInt(marqueediv.style.left)-pxptick+"px";
// If it's at the end, move it back to the right.
else
marqueediv.style.left=parseInt(marqueewidth)+"px";
}
window.onload=startmarquee();
</script>
when iam running the above code on server, iam getting javascript error as "object required" at line 46 also the alert("marqueediv"+marqueediv); is "marqueedivnull" after that alert iam getting the javascript error.
Here my question is, did the div tag is not getting recognized?why?
so that only it is getting as null object, how can i resolved this?
Thanks.
You are calling startmarquee immediately and trying to assign its return value (undefined) to window.onload.
Presumably the script appears in the <head> and this the div does not exist at the time you run it.
Assign the function to onload, not its return value.
window.onload=startmarquee;
You could copy the script and put it before the body closing tag and remove window.onload=startmarquee(); thus making sure all elements have been loaded and accessible
Just like #Quentin said, that element with the id might not have been loaded into the DOM when you referenced it
I am trying to auto generate pages.
What I am trying to do is make a upload form for an image upload that's displayed in a gallery.
I have this but I then want each image to have a page hyper-link auto made for each image where the image can be seen bigger with buying information that's also been uploaded to a MySQL table not 100% with codeigniter I am still luring please look at the site I am trying to build at http://www.fresherdesign.co.uk/PIFF/index.php/main/gallery
This is a direct link to the gallery that I would link to make the page's from, currently they just open a direct link to the image on its own
Any help would be awesome thanks to everyone in advance
Alan Morton
If you want the actual images to be uploaded (and not stored in the database - note that db storage is slightly more difficult to accomplish than your standard upload), you can create a field in the database for the image's location; that is how you are going to correspond your image data with your page content.
Now, if you want a hyperlink to automatically be made, I suggest querying the database of all "Active" entries (again, could be another field unless you simply delete old entries). Each entry should have a unique ID associated with it. This way, when you give the list, simply include a tag similar to
while($row = mysql_fetch_array($query_result)){
// Change this to whatever formatting you need
print '<!-- Whatever content for link -->';
}
Now that's just your loop to get the results. The actual page now should query the database based on the ID given. The query should grab the page content from the database. Something like this would work
<?php
if(!isset($_GET['id'])){
die("Please use a valid link!");
}
$q = mysql_query("SELECT * FROM YOUR_DB_TABLE WHERE ID='".mysql_real_escape_string($_GET['id'])."' LIMIT 1;");
if(!$q || mysql_num_rows($q) < 1){
die("A MySQL Error Occurred: ".mysql_error());
}
while($row = mysql_fetch_array($q)){
// Again, adjust this accordingly
print "Data column 1: ".$row['DataRow1']."<br />".
"Data Column 2: ".$row['DataRow2']."<br />".
"<img src='".$row['ImageLocation']."' />";
}
?>
Now, I haven't tested this exact code, however all of it should work as is. But you will need to adjust it appropriately to fit your requests; but this is one way to accomplish what you're looking for.
Precondition
You'll need to have the directory name in which things are stored, relative to where your php page is located. Obviously, you have this already to create the page. I will assume it is stored in the $dir variable.
Code
if ($handle = opendir($dir)) {
while (false !== ($file = readdir($handle))) {
echo "<a href='http://www.mydomain.com/".$dir."/".$file."'>";
echo "<img src='http://www.mydomain.com/".$dir."/".$file."' />";
echo "</a>";
}
}
Output
This will provide you a list of images that link to the image file itself.
Possible Modifications
1) You may want to only show some of the files in the directory, or a certain amount: Use the if block added here to do that:
if ($handle = opendir($dir)) {
//set $strThatSpecifiesImages to whatever you want;
//for the example, I'm saying that we only want to show files with "gal_image" in the filename
$strThatSpecifiesImages = "gal_image";
$maxFilesToShow = 10; //set this to whatever you want; example max is 10
$count = 0;
while (($count < $maxFilesToShow) && (false !== ($file = readdir($handle))) {
if (strpos($file, $strThatSpecifiesImages) > -1) {
echo "<a href='http://www.mydomain.com/".$dir."/".$file."'>";
echo "<img src='http://www.mydomain.com/".$dir."/".$file."' />";
echo "</a>";
$count++;
}
}
}
2) You might also want to change how things are displayed, so that you don't just have the full image shown here every time. Do this by modifying things in the echo blocks that are outputting HTML. You can have the browser resize the images, or just change it completely so that the links use text instead, or something else.
NOTE: This is a long question. I've explained all the 'basics' at the top and then there's some further (optional) information for if you need it.
Hi folks
Basically last night this started happening at about 9PM whilst I was trying to restructure my code to make it a bit nicer for the designer to add a few bits to. I tried to fix it until 2AM at which point I gave up. Came back to it this morning, still baffled.
I'll be honest with you, I'm a pretty bad Javascript developer. Since starting this project Javascript has been completely new to me and I've just learn as I went along. So please forgive me if my code structure is really bad (perhaps give a couple of pointers on how to improve it?).
So, to the problem: to reproduce it, visit http://furnace.howcode.com (it's far from complete). This problem is a little confusing but I'd really appreciate the help.
So in the second column you'll see three tabs
The 'Newest' tab is selected by default. Scroll to the bottom, and 3 further results should be dynamically fetched via Ajax.
Now click on the 'Top Rated' tab. You'll see all the results, but ordered by rating
Scroll to the bottom of 'Top Rated'. You'll see SIX results returned.
This is where it goes wrong. Only a further three should be returned (there are 18 entries in total). If you're observant you'll notice two 'blocks' of 3 returned.
The first 'block' is the second page of results from the 'Newest' tab. The second block is what I just want returned.
Did that make any sense? Never mind!
So basically I checked this out in Firebug. What happens is, from a 'Clean' page (first load, nothing done) it calls ONE POST request to http://furnace.howcode.com/code/loadmore .
But every time you load a new one of the tabs, it makes an ADDITIONAL POST request each time where there should normally only be ONE.
So, can you help me? I'd really appreciate it! At this point you could start independent investigation or read on for a little further (optional) information.
Thanks!
Jack
Further Info (may be irrelevant but here for reference):
It's almost like there's some Javascript code or something being left behind that duplicates it each time. I thought it might be this code that I use to detect when the browser is scrolled to the bottom:
var col = $('#col2');
col.scroll(function(){
if (col.outerHeight() == (col.get(0).scrollHeight - col.scrollTop()))
loadMore(1);
});
So what I thought was that code was left behind, and so every time you scroll #col2 (which contains different data for each tab) it detected that and added it for #newest as well. So, I made each tab click give #col2 a dynamic class - either .newestcol, .featuredcol, or .topratedcol. And then I changed the var col=$('.newestcol');dynamically so it would only detect it individually for each tab (makin' any sense?!). But hey, that didn't do anything.
Another useful tidbit: here's the PHP for http://furnace.howcode.com/code/loadmore:
$kind = $this->input->post('kind');
if ($kind == 1){ // kind is 1 - newest
$start = $this->input->post('currentpage');
$data['query'] = "SELECT code.id AS codeid, code.title AS codetitle, code.summary AS codesummary, code.author AS codeauthor, code.rating AS rating, code.date,
code_tags.*,
tags.*,
users.firstname AS authorname,
users.id AS authorid,
GROUP_CONCAT(tags.tag SEPARATOR ', ') AS taggroup
FROM code, code_tags, tags, users
WHERE users.id = code.author AND code_tags.code_id = code.id AND tags.id = code_tags.tag_id
GROUP BY code_id
ORDER BY date DESC
LIMIT $start, 15 ";
$this->load->view('code/ajaxlist',$data);
} elseif ($kind == 2) { // kind is 2 - featured
So my jQuery code sends a variable 'kind'. If it's 1, it runs the query for Newest, etc. etc.
The PHP code for furnace.howcode.com/code/ajaxlist is:
<?php // Our query base
// SELECT * FROM code ORDER BY date DESC
$query = $this->db->query($query);
foreach($query->result() as $row) {
?>
<script type="text/javascript">
$('#title-<?php echo $row->codeid;?>').click(function() {
var form_data = {
id: <?php echo $row->codeid; ?>
};
$('#col3').fadeOut('slow', function() {
$.ajax({
url: "<?php echo site_url('code/viewajax');?>",
type: 'POST',
data: form_data,
success: function(msg) {
$('#col3').html(msg);
$('#col3').fadeIn('fast');
}
});
});
});
</script>
<div class="result">
<div class="resulttext">
<div id="title-<?php echo $row->codeid; ?>" class="title">
<?php echo anchor('#',$row->codetitle); ?>
</div>
<div class="summary">
<?php echo $row->codesummary; ?>
</div>
<!-- Now insert the 5-star rating system -->
<?php include($_SERVER['DOCUMENT_ROOT']."/fivestars/5star.php");?>
<div class="bottom">
<div class="author">
Submitted by <?php echo anchor('auth/profile/'.$row->authorid,''.$row->authorname);?>
</div>
<?php
// Now we need to take the GROUP_CONCATted tags and split them using the magic of PHP into seperate tags
$tagarray = explode(", ", $row->taggroup);
foreach ($tagarray as $tag) {
?>
<div class="tagbutton" href="#">
<span><?php echo $tag; ?></span>
</div>
<?php } ?>
</div>
</div>
</div>
<?php }
echo " ";?>
<script type="text/javascript">
var newpage = <?php echo $this->input->post('currentpage') + 15;?>;
</script>
So that's everything in PHP. The rest you should be able to view with Firebug or by viewing the Source code. I've put all the Tab/clicking/Ajaxloading bits in the tags at the very bottom. There's a comment before it all kicks off.
Thanks so much for your help!
I think you're right to suspect this code block:
var col = $('#col2');
col.scroll(function(){
if (col.outerHeight() == (col.get(0).scrollHeight - col.scrollTop()))
loadMore(1);
});
My take on this is that you keep adding additional event handlers (duplicates, essentially) each time you run this code. You need to remove (unbind) the existing event handlers with every tab click so that you can be sure that it's only firing once:
$('#col2').unbind();
var col = $('#col2');
col.scroll(function(){
if (col.outerHeight() == (col.get(0).scrollHeight - col.scrollTop()))
loadMore(1);
});
Or some such thing. See http://api.jquery.com/unbind/
$('.featurecol'); , $('.topratedcol'); and $('.newestcol'); all refer to the same column and division (<div>). As such, whenever you switch pages, you need to unbind the old scroll before rebinding the new scroll handler. (Or else you'll be appending another scroll handler and getting multiple requests sent, like now)
You can do this by adding an unbind as follows:
var col = $('.newestcol');
col.unbind('scroll');
col.scroll(function(){
if (col.outerHeight() == (col.get(0).scrollHeight - col.scrollTop()))
loadMore(1);
});
You need to do this for all of the columns as they load (code/newest, code/toprated and code/featured).
It could also be
$('#col3').fadeOut('slow', function() {
as the ajax loads there... n number of times as it fades out it calls another ajax request.
not saying its the defenet answer but something looking into...