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>
Related
I am using this code for refresh my main DIV in my main page (named readings.php):
jQuery(document).ready(
function intervalle() {
setInterval(jQuery('#myMainDiv').load('readings_content.php'), 10000);
});
In the readings_content.php, sensor readings are being checked from database and drawing a screen like a security cam screens according to the sensor count. This code is like:
$db_sensors->query("select * from tbl_sensors where status=1");
if ($db_sensors->recordcount>0){
while ($db_sensors->nextrow()){
$sensors=$db_sensors->fields;
$sensorname = $sensors["name"];
$sensorvalue = $sensors["lastreading"];
echo "<div>";
echo "Sensor Name: ".$sensorname."<br>";
echo "Last Reading: ".$sensorvalue;
echo "</div>";
}}
This idea is working fine. But because of this loop (there are 9-16 sensors) refresh is taking time. That is normally fine because page is not reloading, just changing the values when it reads a new sensor reading. But there is a button in the my main page (readings.php). It takes almost 10 second for response time for this button even I am using local database.
I want to make this refresh process faster. Or if that is possible, I want to stop this refresh thing (or what ever is happening in the page) when I click the button. and make its onClick event working.
After my whole researches I started to try all different options. And it only was OK when I change the jQuery code like this:
setTimeout('sensorcells_load()', 10000);
function sensorcells_load()
{
jQuery('#sensorcells').load('dashboard_content.php');
setTimeout('sensorcells_load()', 10000);
}
I am not a jQuery man and I don't really know why this one works but other one doesn't. But this solved my issue.
On my website an user is able to fill in an url. When he fills in the url, he gets all the images src's from that url. I push these src's to an array in php:
array_push($goodfiles,$pic);
Now the user will be able to choose on of the pictures (with a next or prev button) and then save it to the database. The picture that's saved is based on the id of the image in the array. So $goodfiles['0'] means id = "0" and so on.
I want the swapping of the images to work with ajax, so that the pages doesn't have to refresh all the time when clicking the next or previous button. And then when I save the form, I want to know the id of the current image, so that I can save it to the database.
How do I realize this with Ajax (jquery)?
Edit:
This is how I do it right now:
$current_id = $_GET['id'];
if(empty($_GET['id']) || !empty($empty)) { $current_id = 0; }
$prev_id = $_GET['id'] - 1;
if($prev_id < 0){ $prev_id = 0;}
$next_id = $_GET['id'] + 1;
if($next_id > $_SESSION['count']-1 && $_SESSION['count'] != 'empty') { $next_id = $_SESSION['count']-1;}
This is the code for the pagination
And this is the pagination:
<div id="url_pic">
<img src="<?=$_SESSION['pictures'][$current_id]?>" class="img_load"><br>
<? if($_SESSION['count'] > 1) { ?><center><img src="img/add/left.png"> <img src="img/add/right.png"></center> <? } ?>
</div>
So right now my solution doesn't contain any javascript, but it's all php coded. And the page refreshes everytime you want to see the next picture. I want to solve this in ajax, so that you can paginate through the images without a refresh. The way I want it is like this link:
http://d-scribe.de/webtools/jquery-pagination/demo/demo_options.htm
But except for the text, I want to paginate through images.
You probably don't need to use AJAX for this. Simply return a html file containing a JavaScript array, which contains all those image URLs and do the other stuff using JavaScript.
Get back to StackOverflow in case you've a more precise question and hopefully some code, which we can help on ;)
Load a script at the bottom of your php page the user side of the PHP where all your HTML is, above the closing body tag thats something loosely similar to this
<script type="text/javascript">
var myArray = <?php echo json_encode($myPHParray); ?>
</script>
this way when your page loads out it renders with a dynamic javascript json object as a variable that you can work with client side, this removes the need for an AJAX request all together unless your doing stuff with the data your playing with. From first glance Im guessing not really per say. But yea, at the very least its one less transaction to be made when the page is loading.
edit just noticed someone said similar while I was typing out.. Lars.. so I guess this is a follow up to his answer :-D
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(); ?>">
I am using an Jquery Ajax call to deliver a file download to site users. The process is:
1)Users select various files they want, by clicking on them
2)I store their selections in a mysql database
3)I have a div panel on the right of the page that lists their files (like a basket) and provides a download button
4)If they click on the button, it runs a jquery ajax call to a php file to create a zip file, load all their selected files into the zip and then close the zip. Finally return the zip filename in json.
5)success: then fires a window.open to force the download
This all basically works, but there's a weird problem I can't work out and it's killing me!
Here's the bits of code:
First javascript:
//download files in a zip
$("#zipdownload").click(function(){
$.ajax({
type: "GET",
url: "zipdload.php",
dataType: "json",
cache: false,
success: function(data) {
//opens a small window for IE security thing
window.open(data.archive,'download','left=20,top=20,width=300,height=20,toolbar=0,resizable=0');
// then clears all the divs to simulate the bag emptying
$('#bagCounter').text("Empty!");
$('#zipdownload').text("");
$('#item-list').text("");
}
});
});
Then the layout:
//styled containers to create a sliding panel with a clickable tab
<div id="rightpanelouter">
<div id="rightpanelinner">
<?php if ($_SESSION['username']){
echo $_SESSION['username'].'<br>Toolbox';
};
?>
<div id="bagContents">
<div id="item-list">
<br> Show Bag
//PHP to generate list of files
</div>
<br><br>
<div id="zipdownload" style="cursor:pointer;">
//this element has the action attached to fire function.
<?php
if ($numOfBagDocs != 0){
echo 'Download';
}
?>
</div>
</div>
If anyone is interested I can attach the PHP script too but I'm guessing that's not the problem.
The problem:
The script appears to run twice (at least).
I initially appended the zip filename with a now() stamp so they were always different. but I noticed sometimes the window.open tried to download a file with a now() stamp 1sec different to the saved file.
I then tried to change to a rand() number and that showed two different random numbers!
So I removed the append so the filename was always the same (just appended with the username) and that downloaded but simply kept appending the same zip file with new entries. All that would do is make the zip grow and grow.
So I tried to put a 'file_exists' and 'unlink in to delete the file before creating a zip. All that seemed to do was delete the file AFTER creating the zip and before the jscript download started !!! :-(
All this tells me the script is being called at least twice.
I've seen many entries similar to this but I can't seem to understand whether they apply to my problem. Once suggestion was to chain an 'unbind' before the click function and that just stopped it working, so no good.
The HTML I've attached is pretty much straight after the body tag and there are no other javascript calls within this section.
So apologies if there's a really dumb mistake here, but I've now spent many hours scouring around and just can't work it out.
I would REALLY appreciate any help. Thank you in advance.
So I've got to the bottom of it, without really understanding why. Lack of proper javascript education I guess!
The problem was related to me loading a page from another page using a .load and linking the relevant JScript in the second page. However the DIV being clicked was inside the initial page (I remember now I moved it for aesthetic reasons).
So I moved the click function to the Jscript being called from the initial page itself and he presto it now only fires once!
So I don't understand why that would make a difference but it does, so I happy I can proceed.
Thanks for reading and I hope it helps someone else one day !
I had the same issue. I solved it by adding
evt.stopImmediatePropagation();
to the function. Of course you have to add the evt to the function like:
$(document).on("click", "a.className", function (evt) {
evt.stopImmediatePropagation();
$.fileDownload($(this).prop('href'), {
preparingMessageHtml: "File prepared...",
failMessageHtml: "Error!",
});
return false;
});
It seems to occur, because there are nested elements which fire this event many times.
See jQuery Click fires twice when clicking on label
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 <.