Refreshing Image with JQuery or Javascript - php

I'm trying to get a dynamic image file to refresh every 20 seconds or so, preferably with JQuery/JS but I am open to any suggestions.
The image is a Twitch.tv .php file that dynamically changes from ONLINE to OFFLINE depending on if the streamer is currently broadcasting or not. The problem is that the images don't update sometimes without a slew of browser refreshes, and sometimes they won't update at all until I clear the cache.
The website I'm trying to do this on is http://www.team-omen.com/content.php
You will see in the center a module called OmenTV which has several of these images and I would like to have these automatically update so users don't have to refresh the page to see if the streamer has started broadcasting or not.
This is from the status.php file which determines which .png to display...
<?php
header('content-type: image/png');
$stream = $_GET['stream'];
$json_file = #file_get_contents("http://api.justin.tv/api/stream/list.json?channel={$stream}", 0, null, null);
$json_array = json_decode($json_file, true);
if ($json_array[0]['name'] == "live_user_{$stream}") {
echo file_get_contents("online.png");
}else{
echo file_get_contents("offline.png");
}
?>
And here is the section of the HTML file that displays the images
<div align="center" id="streamers">
<div id="omentoggle" class="streamer">
Team Omen
<br />
<img src="http://www.team-omen.com/status/streamstatus.php?stream=teamomen" class="status" id="status_teamomen" />
</div>
<div id="briantitantoggle" class="streamer">
BrianTitan
<br />
<img src="http://www.team-omen.com/status/streamstatus.php?stream=o_briantitan" class="status" id="status_briantitan"/>
</div>
</div>
...and so on
Can someone give me an example of how to get this to work, say the image in question has an ID of #status_teamomen ?
Thanks in advance

You can use setInterval function in JavaScript to update the image source periodically:
setInterval(function() {
var cache_buster = Math.random();
document.getElementById("status_teamomen").src = "http://www.team-omen.com/status/streamstatus.php?stream=teamomen&cache_buster=" + cache_buster;
}, 20000);
Note the use of a cache buster querystring parameter to generate a unique URL on each request, which will bypass any browser caching of the dynamically generated images.

For the cache problem you could add a random piece in the url so the url is different each time and the image wont get cached by the browser.
See the answer here:
Multiple GD images per page

Related

Difficulty Trying to Refresh Page with PHP

With my limited HTML skills I've hacked together a crude bit of code to accomplish a simple task. I have a Raspberry Pi running an Apache webserver. On the Pi's monitor I need to display an image. Occasionally I will need to change that image remotely, switching between at most maybe a couple dozen images.
Right now in the same directory I have the image page, four .jpg files, and a 'chooser' page to select the image I want. I'm pulling this up on a different computer on the same network. The only way I could figure out how to pass the image I want was to write it to a text file. So the chooser page has a simple web form with some radio buttons and a submit button. You pick a number from 1 to 4, hit submit, and it simply writes that number to the text file. That part works.
The image page opens the text file, reads the number, and tacks it onto the img src tag. I made a simple loop that was refreshing the page every 5 seconds, and that worked fine. I could change the text file and a few seconds later the page would reload with the new image. Awesome.
So I tried to add a little extra code with the idea that instead of refreshing every 5 seconds, it would instead check every 5 seconds to see if the number in the text file was different.
Something about my code is janky, because the first time I load it nothing happens. The browser loading animation is going so I assume the code has started its loop, but if it got that far, why didn't it load the image first? It will churn along until I use the chooser page to change the text file. At that point, it will load the image, but it loads the number that was previously in the text file, not the current one. It works like this each time, always changing to the previous number, not the current one.
I'm sure it's something dumb that I don't understand because my coding skills suck. Anyone see the glaring error?
<?php
$file = fopen("hints.txt","r");
$theData = fread($file,2);
fclose($file);
?>
<img width=533 height=355 src="<?php echo $theData?>.jpg"><br>
<?php
do{
sleep(5);
$file2 = fopen("hints.txt","r");
$theData2 = fread($file2,2);
fclose($file2);
} while ($theData == $theData2);
header("Refresh:0");
?>
Echo a bit of javascript to do it, as I recall headers can only be used before content is put onto the page.
<?php echo "<script>window.location.reload();</script>"; ?>
Your php code is trying to generate a page for the browser, but because you have a loop inside, it will hang there until data changes
Instead, you should poll hints.txt file with javascript ajax requests and update img source from the client side. Something like:
<!-- load source first time from file with php -->
<img width=533 height=355 id="image" src="<?php echo $theData?>.jpg" />
<script type="javascript">
window.setInterval(function(){
//create ajax request object, not useful for IE
var xhttp = new XMLHttpRequest();
//you may want to change URL to this file
xhttp.open("GET", "hints.txt", true);
xhttp.onreadystatechange = function() {
if (xhttp.readyState == 4 && xhttp.status == 200) {
console.log(xhttp.responseText); //see what response was
//change image attribute
document.getElementById("image").src = xhttp.responseText + '.jpg';
}
};
xhttp.send();
//update every 5 sec
},5000);
</script>

uploading image and displaying

I have a script to upload an image and display it. When i choose an image and click upload, it doesn't update the current image, but if i press f5 it will change the current image... thank you very much in advance. im just new in php.
<br><br><input type='submit' name=save value=save onClick='alert(\"Profile Updated!\")'><input type='hidden' name='id' value=$id>";
your browser is probably reusing the cached image, the best way to fix this is to add a unique tag at the end of the image url e.g.
in php i would generally have some kind of helper to do this e.g(very basic):
**
function image_tag($url,$attrs){
$id = abs((int)(microtime(true)*1000)) ); //bit overkill
return '<img src="'.$url.'?'.$id.'" '.$attrs.' />';
}
echo image_tag('some_url.jpeg',' class="my_image_class" ');
**
if you are updating the image with javascript try do something like the following:
**$('#some_img').attr('src',some_url+'?'+(+new Date()));**
should do the trick
can you display image like ??
if yes then you have to append time() so it will loaded properly for example display image like ">
if you just upload image using AJAX then get back image data and fill in to image object.
Here you use profile.php page for upload image so after that you have to redirect that page or reload.
for example after upload image put code header('location:index.php?msg=imageuploaded');

How to prevent old images from appearing on page reloads when there are updated images available

I constantly have to update main images on my site, the user will go to the site but the images won't be the updated versions unless they manually hit refresh. Even by me putting "please hit refresh to view updated images" the users ignore this and I have to e-mail them to hit the refresh button. I've tried having the initial index.html reload to the actual site using Javascript like this
The initial index.html:
document.location.href='index2.php?code=reload_page'
Then on the index2.php:
$the_code = $_GET['code'];
if($the_code == "reload_page")
{
$page = $_SERVER['PHP_SELF'];
$sec = "1";
header("Refresh: $sec; url=$page");
}
else
{
//load page regular
}
I tried it like this, but it didn't work, still has old images until you hit the refresh button. Any other ways of accomplishing this using PHP or javascript/jquery?
The problem with images not refreshing might be an issue with caching in web browser or on the server proxy etc. It is configuration issue and might be not dependant on you. Easy trick to bypass this is to add timestamp to img url. Every time you regenerate your content in index.php just add some query string to your image as this:
<?php
echo '<img src="my_image.png?ts='.time().'" />';
?>
it will trick your browser and proxies on the way that it is another image and prevent caching.
You can use timer to reload your images and get them via AJAX reqest form the other page:
setInterval(function(){
$.ajax({
url: 'index2.php'
}).done(function ( data ) {
$('#image-div').html(data);
});
}, 10000); // wait 10 seconds
Take a look at jQuery.ajax
Put the following in the head section of your page this will reload your content every 5 seconds.
<meta http-equiv="refresh" content="5">
If the browser still caches the images because the url hasn't changed then place a random query string on the end of the image url. You could use a timestamp.
<img src="image.jpg?<?php echo time(); ?>">

jQuery / PHP - Lazy loading gallery keeps trying to fetch images even when they've all loaded

I've got an image gallery that is showing one image per row inside of a div. I don't want the next image to load until it reaches the edge of the viewport (to save on server resources). All the images are named sequentially in the same folder (img/1.jpeg, img/2.jpeg, img/3.jpeg, ...).
I'm using a modified jQuery plugin to do this, but it still keeps trying to fetch the next image after all the images in the directory have been loaded. It's the last if statement I'm having trouble with here.
How do I stop the function from running once the last image in the directory has loaded?
<?php
// Count total number of images in the directory
$directory = "img/";
$totalImages = count(glob("" . $directory . "*.jpeg"));
?>
<script type="text/javascript">
$('document').ready(function(){
scrollalert();
});
function scrollalert(){
var scrolltop=$('#scrollbox').attr('scrollTop');
var scrollheight=$('#scrollbox').attr('scrollHeight');
var windowheight=$('#scrollbox').attr('clientHeight');
if(scrolltop>=(scrollheight-(windowheight)))
{
// Fetch next image
var nextImgNum=$('#content img').length + 1;
$('#content').append('<img src=\"book1/'+nextImgNum+'.jpeg\" /><br />');
updatestatus();
}
if(nextImgNum<=<?php echo $totalImages ?>)
{
setTimeout('scrollalert();', 0);
}
}
</script>
Any tips to optimize this script are greatly appreciated too :)
That script is highly inefficient and keeps the browser quite busy. You're basically in a tight loop checking whether the user has scrolled the page and avoiding the browser's script timeout via the use of setTimeout(). This is not something I would recommend. You can definitely fix this issue, but why not use the jQuery Lazy Load plug-in?
http://plugins.jquery.com/project/lazyload
Be careful with the lazyload plugin, it doesn't work properly with webkit.
See Bug 6656 (this bug may also be related to your problem) and the project page for Lazyload
Change your comparison operator from <= to <.

How to display images when a link is clicked using JQuery, PHP & MySQL?

Lets say a member is displaying 10 images by default but a link will display the rest of the users images by having them slide down when a user clicks a link.
So my question basically is I want to be able to display all the users images buy having them slide down when a user clicks on a link <a>. How would I be able to tackle this problem using JQuery, PHP & MySQL?
check this plugin, it's not what you asked, but it's (IMO) a better solution
http://www.appelsiini.net/projects/lazyload/enabled_fadein.html
BTW : PHP and MySQL are arbitrary in that question since it depends how your images are stored on the server
This will take care of it.
<script>
$(document).ready(function() {
$(".more").toggle(
function() {
$(this).text('less');
$(this).parent().children(".bottom_images").slideDown("fast");
return false;
},
function() {
$(this).text('more');
$(this).parent().children(".bottom_images").slideUp("fast");
return false;
});
});
</script>
<style>
.bottom_images {
display: none;
}
</style>
<div class="container">
<div class="top_images">
<?php
//num images to originally display
$num_show=10;
//current position
$i=1;
//some code to get user images
//from database etc
foreach($images as $image_url) {
if($i==10) {
echo '</div><div class="bottom_images">';
}
echo '<img src="'.$image_url.'" />';
$i++;
}
?>
</div>
more
</div>
Obviously there is some pseudo code for retrieving the user images as there are a number of ways you could get the images eg. from database (as a blob or text url), scanning the file system, user input etc etc. Also I have made it so you can add multiple containers (multiple users) into the one page.
It depends on various aspects how do you want to do it.
You can use LazyLoading as provided by Yanick Rochon
You can preload all the images and simply show the hidden ones when
clicked.
You can also load additional images using AJAX
You can load the visible images first and after all they're loaded - preload invisible images so to show them instantly after clicking a link
Describe your problem a little bit deeper.

Categories