Auto refresh JavaScript function stop working after some time - php

i need to refresh image in every 5 sec. without flicker. so search google and find some solution.
but that Code refresh image and without flicker but it stop refresh image after some time.
some time its stop refresh image after 1 min, some time after 3 min some time after 15 min.
Here is my code
<head>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
<title></title>
<script language="JavaScript">
var x = 0,
y = 0;
var canvas, context, img;
function timedRefresh() {
canvas = document.getElementById("x");
context = canvas.getContext("2d");
img = new Image();
img.src = "CC4.png?" + Math.random();
img.onload = function () {
context.drawImage(img, x, y);
x += 0;
y += 0;
setTimeout('timedRefresh()', 5000);
};
}
window.onload = timedRefresh;
</script>
</head>
<body id="home" onload="setTimeout('timedRefresh()',5000)">
<canvas id="x" width="800" height="590"/>
</body>
</html>

I guess it is a network issue so it stops when it can't load the image. Try adding
img.onerror = function(){ setTimeout('timedRefresh()', 1000); }
so it retries the load even if there was an issue

Related

on size change remove the existing image and add other image dynamically without reloading the page

I am building a website. In that I am using bootstrap carousel in which I am adding images dynamically according to the orientation of the screen.
By JavaScript I am measuring the width and height of the screen and posting the width, height, and id to the php via ajax.
in php the width, height, id is received, php is fetching all the data from the mysql table with respect to the id.
if width is greater then height then it is landscape orientation and it converts all the values under landscape column into json.
Otherwise it is portrait orientation and it converts all the values under portrait column into json.
The ajax calls back the json data and appends it to the data correctly.
My problem is while the screen is in landscape mode it shows all the landscape images (example 5 images). When the orientation is changed to portrait the ajax works and fetches the portrait images (example 5 images) and adds to the existing landscape images resulting in 10 images. If i change the orientation again, landscape images are added again resulting in 15 images. After refreshing the page only 5 images are shown with respect to the orientation.
How to get this without refreshing the page (when the orientation is changed from landscape to portrait, all landscape images should be removed and portrait images should be added without refreshing the page).
<html>
<head>
<title></title>
<meta name="viewport" content="width=device-width, initial-scale=1">
<link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/css/bootstrap.min.css">
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.2.1/jquery.min.js"></script>
<script src="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/js/bootstrap.min.js"></script>
</head>
<body onresize="send_screen_size()" onload="send_screen_size()">
<div class="container">
<div id="myCarousel" class="carousel slide" data-ride="carousel" >
<div class="carousel-inner"></div>
</div>
</div>
</body>
</html>
function send_screen_size(sParam){
var sPageURL = window.location.search.substring(1);
var sURLVariables = sPageURL.split('&');
for (var i = 0; i < sURLVariables.length; i++)
{
var sParameterName = sURLVariables[i].split('=');
if (sParameterName[0] == sParam)
{
return decodeURIComponent(sParameterName[1]);
}
}
if(window.innerWidth !== undefined && window.innerHeight !== undefined) {
var w = window.innerWidth;
var h = window.innerHeight;
} else {
var w = document.documentElement.clientWidth;
var h = document.documentElement.clientHeight;
}
var
width = + w ;
height = + h;
var width = width = + w ;
var height = height = + h;
var pro_id = send_screen_size('pro_id');
$.ajax({
async : "false", // !!!MAKE SURE THIS ONE IS SET!!!
type:"POST",
url: "carousel.php",
data:{width: width, height: height, pro_id:pro_id},
dataType: 'json',
success: function (data){
$.each(data, function(i, item) {
$('.carousel-inner').append('<div class = item>'+item.orientation+'</div>')
})
$('.carousel-inner > :first-child').addClass("active");
},
error: function(xhr, status, error) {
var err = eval("(" + xhr.responseText + ")");
console.log(error);
}
});
}
You could try
$('.carousel-inner .item').remove();
before $.ajax call.
You might want to throttle or debounce your window onresize event listener also.

"Automatically update time in PHP using Ajax - display

I wish to show the current local time on my weather web site.
This is the code that I use from a query :"Automatically update time in PHP using Ajax" posted 2 years ago
<?php
echo "<html>
<head>
<title>Realtime clock</title>
<meta charset='UTF-8'>
<meta name='viewport' content='width=device-width, initial-scale=1.0'>
<script src='http://code.jquery.com/jquery.js'></script>
<script>
$(document).ready(function(){
setInterval(_initTimer, 1000);
});
function _initTimer(){
$.ajax({
url: 'timer.php',
success: function(data) {
console.log(data);
data = data.split(':');
$('#hrs').html(data[0]);
$('#mins').html(data[1]);
$('#secs').html(data[2]);
}
});
}
</script>
</head>
<body>
<span id='hrs'>0</span>:<span id='mins'>0</span>:<span id='secs'>0</span>
</body>
</html>"; ?>
<?php date_default_timezone_set("Australia/Brisbane");
echo "Current Time: ". date("H:i:s"). " AEST";
?>
This is what I getwhen I run this:
17:05:10 Current Time: 17:01:30 AEST
What I am aiming to achieve is:
Current Time: 17:05:10 AEST with the time updating every second.
Is there some addition that I need to make in the final echo statement? Or do something else
please help
Thanks
To show current time every second you could use jquery to show time, instead of running ajax on server for every second
Try this:
var nIntervId;
function updateTime() {
nIntervId = setInterval(flashTime, 1000);
}
function pad(n) { return ("0" + n).slice(-2); }
Number.prototype.pad = function (len) {
return (new Array(len+1).join("0") + this).slice(-len);
}
function flashTime() {
var now = new Date();
var h = now.getHours().pad(2);
var m = now.getMinutes().pad(2);
var s = now.getSeconds().pad(2);
var time = h + ' : ' + m + ' : ' + s;
$('#my_box1').html(time);
}
$(function() {
updateTime();
});
<script type="text/javascript" src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.2.1/jquery.js"></script>
<div id="my_box1">
</div>
I assume you have made a separate timer.php file just to echo server time. As your current page is loading just once, the initial server time will not be updated that is your "current time value". Whereas the remaining DOM will be updated with the server time because of ajax code. If you want both times to be same you will have to reload the whole page which is not correct. Hence, I suggest you to display only one time which should be your ajax result.
timer.php:
<?php
date_default_timezone_set("Australia/Brisbane");
echo date("H:i:s");
?>

Parse RSS <link> to use as a source

OK so im trying to have a webpage that rotates every 30 seconds now i have what i need for this but instead of using an array like in what i have now see code below
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
<title>Rotating Page</title>
<style type="text/css">
* {
margin:0;
padding:0;
border:0;
}
html, body, iframe {
height:100%;
width:100%;
overflow:hidden;
}
</style>
<script type="text/javascript">
var pages = new Array(); // this will hold your pages
pages[0] = 'MY-LINK-HERE';
pages[1] = 'MY-LINK-HERE';
pages[2] = 'MY-LINK-HERE';
pages[3] = 'MY-LINK-HERE';
pages[4] = 'MY-LINK-HERE';
pages[5] = 'MY-LINK-HERE';
var time = 30; // set this to the time you want it to rotate in seconds
// do not edit
var i = 1;
function setPage()
{
if(i == pages.length)
{
i = 0;
}
document.getElementById('holder').setAttribute('src',pages[i]);
i++;
}
setInterval("setPage()",time * 1000);
// do not edit
</script>
</head>
<body>
<iframe id="holder" src="MY-SPLASH-PAGE-HERE" frameborder="0" scrolling="no"></iframe>
</body>
</html>
where in MY-LINK-HERE for the pages array i would like to use my rss link and get the list of links and add them to the pages array or something similar
my rss link is http://directitpros.com/cbm/wp/?feedpages
so i just want to load the text in the pages variable
It took me some time but I got it (tested and working)
This example uses jQuery and jGFeed.
jGFeed is a plugin for jQuery to do anything you want with RSS feeds.
In the HTML source you can get the URL of the plugin to save it.
Observations:
1. Your RSS link is not working properly, please check it!
(http://directitpros.com/cbm/wp/?feedpages)
When using your link I receive this error from the plugin I am using in browser console:
"Uncaught TypeError: Cannot read property 'feed' of null"
2. Make sure the links you want to use in iframe are able to browse by iframe:
Example:
If URLs are not able to browse by iframe you will get this message in your browser console and your iframe will be empty:
"Refused to display document because display forbidden by X-Frame-Options."
3. If you find a working RSS url and links from it fit the above requirements, use this live example I made to test:
http://jsfiddle.net/oscarj24/qWdqc/
(Check browser console and check messages that will appear)
Let's go with the code :-)
HTML:
<script src="http://code.jquery.com/jquery-latest.js" type="text/javascript"></script>
<script src="http://dl.dropbox.com/u/15208254/stackoverflow/jquery.jgfeed.js" type="text/javascript"></script>
<iframe id="holder" src="" frameborder="0" scrolling="no"></iframe>​
CSS:
html, body, iframe {
height:100%;
width:100%;
overflow:hidden;
}​
JS:
// Array containing pages
var pages = new Array();
// Time in seconds to rotate pages
var time = 30;
// Variable for loop purpose
var i = 1;
$(function(){
$.jGFeed('http://working-rss-url',
function(feeds){
// Check for feeds
if(!feeds){
// There was an error, remote url not ok or no feeds
return false;
}
// Do whatever you want with feeds here
for(var i=0; i<feeds.entries.length; i++){
var entry = feeds.entries[i];
// Fill array with RSS entries
pages.push(entry);
}
// If array contains urls
if(pages.length != 0){
// Rotate pages every 'x' seconds
setInterval(function() {
if(i == pages.length){
i = 0;
}
// Replace iframe scr with RSS entry link every 'x' seconds
$('#holder').attr('src', pages[i].link);
i++;
}, time * 1000);
}
}, 5); // Number of feeds you want to recover
});
Hope this helps.

Drawing markers on a google map starting from a php array

All right, I'll try to explain my problem as clearly as I can. I already tried a lot of possible solution but never happen to find the right one.
I also want to say this is a tutorial for me, i am just a beginner in combining JS, PHP and GMAPv3 APIs.
I hope that someone can help me in solving this.
That being said, here is my code with a few lines to explain what i want to do.
The problem involves 3 main files.
1) process.php (this file generates an array of coordinates)
<!DOCTYPE html>
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8"/>
<title>MyTest</title>
<link rel="stylesheet" type="text/css" href="css/content.css" />
<script type="text/JavaScript" src="js/gmapinit.js"></script>
</head>
<body>
<?php
...after some lines of code i build this...
$myarray = ...;
...and here i move to the second file
echo "<input type=\"button\" value=\"Next!\" onClick=\"location.href='map.html'\">";
?>
</body>
2) map.html (this file is responsible for drawing the map on the screen)
<!DOCTYPE html>
<html>
<head>
<meta name="viewport" content="initial-scale=1.0, user-scalable=no" />
<title>MyTest</title>
<link rel=stylesheet type="text/css" href="css/googlemap.css" />
<script type="text/javascript"
src="http://maps.googleapis.com/maps/api/js?key=AIzaSyCbNM4y2fJ4AdCoXcWW-sGXPl5nXaJogPA&sensor=false">
</script>
<script type="text/JavaScript" src="js/gmapinit.js"></script>
<script type="text/javascript" src="http://www.google.com/jsapi"></script>
</head>
<body onLoad="init_map_and_markers()">
<div id="map_canvas">
</div>
</body>
2) gmapinit.js (the javascript file that builds the map and "should" get the array as parameter to draw markers accordingly)
function init_map_and_markers() {
var global_markers = [];
var infowindow = new google.maps.InfoWindow({});
var latlng = new google.maps.LatLng(27.059126, -41.044922);
var myOptions = {
zoom: 3,
center: latlng,
mapTypeId: google.maps.MapTypeId.HYBRID
};
var map = new google.maps.Map(document.getElementById("map_canvas"),
myOptions);
//Of course here myarray is not defined but the point is making it available here so i can loop through it and place my markers!
for (var i = 0; i < markers.length; i++) {
for(var count = myarray.length - 1; count >= 0; --count) {
var o = myarray[count];
var lat = parseFloat(o.lat);
var lng = parseFloat(o.lng);
var markerdata = o.user;
var myLatlng = new google.maps.LatLng(lat, lng);
var contentString = "<html><body><div><p><h2>" + markerdata + "</h2></p></div></body></html>";
var marker = new google.maps.Marker({
position: myLatlng,
map: map,
title: "Coordinates: " + lat + " , " + lng + " | Marker Data: " + markerdata
});
marker['infowindow'] = contentString;
global_markers[i] = marker;
google.maps.event.addListener(global_markers[i], 'click', function() {
infowindow.setContent(this['infowindow']);
infowindow.open(map, this);
});
}
}
}
So the main question is, how can i pass $myarray from process.php to map.html making it available to gmapinit.js???
I am asking this avoiding to write down all code-tests i did because maybe my all thinking is wrong...that's why i am writing down the most "clean" code i got.
Code possible solutions would be much appreciated, and don't hesitate to ask for details if i missed something.
Thanks a lot.
you may use the markers as argument for init_map_and_markers()
<body onLoad="init_map_and_markers(<?php echo json_encode($phpArrayMarkersDefinition); ?>)">
..then you may access this array inside the function:
function init_map_and_markers(markers)
{
//....
for(var i=0;i<markers.length;++i)
{
//create the markers here
}
//....
}

Browsed Time Problem

I want to display the browsed time of a user, But when i refresh it, it will be again start from 0:0:0.
How can it handle?
<?php
$total_mints=($live_match['match_name']) * (60);
?>
<script language="javascript">
display_c(<?=$total_mints?>,'ct');
</script>
<script type="text/javascript">
function display_c(start,div){
window.start = parseFloat(start);
var end = 0 // change this to stop the counter at a higher value
var refresh=1000; // Refresh rate in milli seconds
if(window.start >= end ){
mytime=setTimeout("display_ct('"+div+"')",refresh)
}
else {alert("Time Over ");}
</script>
Once the time is over, you could set a cookie to 'Time Expired'... When the page is loaded, if the cookie is 'Time Expired' then you can display the 'Time Over' alert. You can also use the cookie to keep track of accumulated browsing time.
Edit - added some specifics... but I think you'll have to think about this some more.
Basically, you want to use JS to write the cookie as the user uses the page, and you want to use PHP to read the cookie when the page is loaded. You can use the cookie to either only track whether time is up, total accumulated time, or both. I think you'd want to renew the cookie every minute or so?
It's going to look SOMETHING like this - this code just shows how to keep track of whether time has expired or not with a cookie, not accumulated time.
<?php
$total_mints=($live_match['match_name']) * (60);
// check for cookie and only proceed if it is not expired
// can also use cookie to keep track of total accumulated number
// of minutes between session
if ($_COOKIE["yourMints"] != "expired")
{
?>
<script language="text/javascript">
display_c(<?php echo $total_mints; ?>,'ct');
</script>
<script type="text/javascript">
function display_c(start,div)
{
window.start = parseFloat(start);
var end = 0 // change this to stop the counter at a higher value
var refresh=1000; // Refresh rate in milli seconds
if(window.start >= end )
{
mytime=setTimeout("display_ct('"+div+"')",refresh)
} else
{
alert("Time Over ");
// set cookie to expired
document.cookie = "yourMints=expired";
}
}
</script>
<?php
} else // What follows is what happens if cookies IS expired
{
?>
<script type="text/javascript">
alert("Time Over ");
</script>
<?php
}
?>
Here is a good JS cookies tutorial:
http://www.quirksmode.org/js/cookies.html
Here is using $_COOKIE to read cookies with PHP
http://php.net/manual/en/reserved.variables.cookies.php
EDIT: Added in JQuery example after seeing PlagueEditor's example.
Nice script PlagueEditor. Thought I'd try the same thing w/ JQuery for fun.
JQuery has a simple little cookie plugin... only 40 lines of code or so.
Here's a page with a cookie stored timer and a timeout of 10 seconds with a possible reset:
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN">
<html>
<head>
<title>Time Spent on Page</title>
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
<script type="text/javascript" src="PATH-TO-YOUR-JQ-DIRECTORY/jquery-1.4.2.min.js"></script>
<script type="text/javascript" src="PATH-TO-YOUR-JQ-DIRECTORY/cookie.js"></script>
<script type="text/javascript">
<!--
$.myTimer =
{
timeLimit: 10,
displayTime: function ()
{
if ($.myTimer.time < $.myTimer.timeLimit)
{
$("#timeHere").html($.myTimer.time);
$.cookie('yourMints', $.myTimer.time, { expires: 7});
++$.myTimer.time;
$.myTimer.toggle = setTimeout("$.myTimer.displayTime()",1000);
} else
{
$("#page").html('<h1>Time expired</h1>');
}
}
}
// When the page is ready ==================================================
$(document).ready(function()
{
// Read time spent on page cookie. Set it, if it doesn't exist.
if (!$.cookie('yourMints'))
{
$.cookie('yourMints', '0', { expires: 7});
}
$.myTimer.time = $.cookie('yourMints');
// Start timeer
$.myTimer.displayTime();
// Reset the timer
$("#reset").click( function()
{
$.cookie('yourMints', '0');
window.location.reload();
});
});
// -->
</script>
</head>
<body>
<div id="page">
<h2>Your total time here: <span id="timeHere"></span></h2>
You can only look at this page for 10 seconds.
</div>
<input id="reset" type="button" value="Reset Timer" />
</body>
</html>
Below is a solution for keeping track of the browsed time, even with refreshing. It gets the date when the page loads and every second subtracts that date from the given date. The date is then displayed in the span. The page should work by itself. I hope this is what you were looking for, or at least helps. Two functions were W3Schools examples*.
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN">
<html>
<head>
<title></title>
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
</head>
<body>
<script type="text/javascript">
/**
* getCookie and setCookie were taken from http://www.w3schools.com/JS/js_cookies.asp.
*/
function getCookie(c_name)
{
if (document.cookie.length>0)
{
c_start=document.cookie.indexOf(c_name + "=");
if (c_start!=-1)
{
c_start=c_start + c_name.length+1;
c_end=document.cookie.indexOf(";",c_start);
if (c_end==-1) c_end=document.cookie.length;
return unescape(document.cookie.substring(c_start,c_end));
}
}
return "";
}
function setCookie(c_name,value,expiredays)
{
var exdate=new Date();
exdate.setDate(exdate.getDate()+expiredays);
document.cookie=c_name+ "=" +escape(value)+
((expiredays==null) ? "" : ";expires="+exdate.toUTCString());
}
var totalTime=0;
var storedTime=getCookie("storedTime");
if(storedTime.length == 0){
//If it doesn't exist..
storedTime=0;
}else{
storedTime=parseInt(storedTime);
totalTime=storedTime;
}
function updateTime(){
totalTime+=1000;
document.getElementById("duration").innerHTML= Math.ceil(totalTime / 1000);
}
onbeforeunload = function(){
setCookie("storedTime",totalTime,3);
}
setInterval(updateTime, 1000);
</script>
Your total time here: <span id="duration"><script type="text/javascript">document.write( Math.ceil(totalTime / 1000));</script></span> seconds...
</body>
</html>

Categories